Jan-23-2019, 12:05 PM
Can anyone help me with Tuple unpacking term? If given example, that will help me to understand more clearly.
Tuple Unpacking
|
Jan-23-2019, 12:05 PM
Can anyone help me with Tuple unpacking term? If given example, that will help me to understand more clearly.
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))
(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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link Create MCV example Debug small programs |
|