Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tuple Unpacking
#1
Can anyone help me with Tuple unpacking term? If given example, that will help me to understand more clearly.
Reply
#2
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 = person
and the variables values are now:
print('Name: {}, age: {}, hobby: {}'.format(name, age, hobby))
Output:
Name: Daniel, age: 18, hobby: chess
Reply
#3
(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

Reply
#4
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
>>> a
1.
>>> b
2.
>>> c
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unpacking a dict with * or ** msrk 4 913 Dec-02-2023, 11:50 PM
Last Post: msrk
  iterate through the dict_values while unpacking the dictionary PeacockOpenminded 3 1,260 Jan-22-2023, 12:44 PM
Last Post: PeacockOpenminded
  Unpacking zip object Mark17 12 3,102 Mar-28-2022, 04:59 PM
Last Post: deanhystad
  unpacking list wardancer84 2 1,837 Sep-11-2021, 02:42 PM
Last Post: wardancer84
  unpacking tuple not working project_science 1 1,451 Jan-09-2021, 09:09 PM
Last Post: buran
  Unpacking a list Mark17 3 2,555 Dec-18-2020, 05:08 AM
Last Post: aajkaal
  Unpacking wheel files DavidTheGrockle 3 10,872 Dec-15-2020, 05:11 PM
Last Post: DavidTheGrockle
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 2,725 Nov-04-2020, 11:26 AM
Last Post: Aggam
  Why the result of "extended iterable unpacking" with set() is unpredictable? zohanlin 2 2,014 Jun-29-2020, 10:30 AM
Last Post: zohanlin
  Unpacking nested lists yonatan776 1 2,158 Apr-14-2020, 08:50 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020