Jan-23-2019, 12:05 PM
Jan-23-2019, 02:10 PM
Let's say you have tuple:
person = ('Daniel', 18, 'chess')then you can unpack these tuple values by assigning them to variables (number of variables must be the same as number of values in tuple), like this (tuple unpacking):
name, age, hobby = personand the variables values are now:
print('Name: {}, age: {}, hobby: {}'.format(name, age, hobby))
Output:Name: Daniel, age: 18, hobby: chess
Jan-23-2019, 02:40 PM
(Jan-23-2019, 02:10 PM)mlieqo Wrote: [ -> ](number of variables must be the same as number of values in tuple)Just to expand a bit. Above is correct, but in python3 you have also extended iterable unpacking. You can do
>>> spam, eggs, *rest = 1, 2, 3, 4 >>> spam 1 >>> eggs 2 >>> rest [3, 4] >>> spam, *foo, eggs = 1, 2, 3, 4, 5 >>> spam 1 >>> eggs 5 >>> foo [2, 3, 4] >>>Note that using asterisks makes the respective variable catch-all.
Jan-30-2019, 12:42 PM
If we have tuple numbers=(1,2,3). We can unpack its values into a, b, and c variables. This is how tuple unpacking can be done:
>>> nums=(1,2,3) >>> a,b,c=nums >>> a1.
>>> b2.
>>> c