python sequence - ghdrako/doc_snipets GitHub Wiki
sequence
task = (1001, "Laundry", 5)
task_id = task[0]
task_title = task[1]
task_urgency = task[-1]
unpacking
task = (1001, "Laundry", 5)
task_id, task_title, task_urgency = task
print(task_id, task_title, task_urgency)
# output: 1001 Laundry 5
user_data = ("python_user", 35, "male")
username, age, gender = user_data
print(username, age, gender)
# output: python_user 35 male
x0, y0 = (90, 20)
(x1, y1) = 90, 20
(x2, y2) = (90, 20)
assert x0 == x1 == x2 == 90
assert y0 == y1 == y2 == 20
starred expression - All items that are not denoted by other variables are captured by the variable.
a, *b, c = "abcdefg"
assert b == ['b', 'c', 'd', 'e', 'f']
first_score, *scores, last_score = [9.1, 8.9]
assert scores == []
One assignment can use only one starred expression.
task = (1001, "Laundry", "Wash clothes", "completed")
task_id, _, _, task_status = task
*
is working as an operator to implement extended iterable unpacking
>>> *[1,2,3], 5
(1, 2, 3, 5)
>>> [*[1,2,3], 5]
[1, 2, 3, 5]
>>> {*[1,2,3], 5}
{1, 2, 3, 5}
*[1,2,3] # SyntaxErro
Iterable unpacking can be only used in certain places. For example, it can be used inside a list, tuple, or set. It can be also used in list comprehension and inside function definitions and calls
extended iterable unpacking(Python 3) - any sequence item that is not assigned to a variable is assigned to the variable following *
a, b, *c = some-sequence
*a, b, c = some_sequence
>>>x, *y, v, w = ['Machine', 'Learning', 'with', 'Python', '1.0.0']
>>>print(x, y, v, w)
Machine ['Learning', 'with'] Python 1.0.0
>>>x, *y, v, w = ('Machine', 'Learning', 'with', 'Python', '1.0.0') # change to tuple
>>>print(x, y, v, w)
Machine ['Learning', 'with'] Python 1.0.0 # still the list