Tuple Unpacking - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Tuple Unpacking (/thread-15590.html) |
Tuple Unpacking - HarshaliPatel - Jan-23-2019 Can anyone help me with Tuple unpacking term? If given example, that will help me to understand more clearly. RE: Tuple Unpacking - mlieqo - Jan-23-2019 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))
RE: Tuple Unpacking - buran - Jan-23-2019 (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. RE: Tuple Unpacking - dukoolsharma - Jan-30-2019 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 |