The process of assigning tuple items into variable is known as unpack (extract) tuples. It also allows to unpack specified number of items and remaining items in tuples by using asterisks.
Unpack items to each variables
An unpack item can be assigned to each variable by specifying multiple variable in simple bracket. Once a tuple item assigned to variable, it can be access individually.
Unpack items to each variable
1 tpl = ("apple", "banana", "cherry")
2
3
4 (f1, f2, f3) = tpl
5
6 print("Item 1 :", f1)
7 print("Item 2 :", f2)
8 print("Item 3 :", f3)
In the above example, a tuple object is created with three different string values. A tuple object extracted into three different variables that will be printed on console.
1 Item 1 : apple
2 Item 2 : banana
3 Item 3 : cherry
Unpack selective items
To unpack selective items from the tuple, it can be achieve by specifying asterisk (*) sign before last variable in the bracket.
Unpack first few tuple items
1 tpl = ("apple", "banana", "cherry", "orange", "kiwi")
2
3
4 (f1, f2, *f3) = tpl
5
6 print("Item 1 :", f1)
7 print("Item 2 :", f2)
8 print("remaining :", f3)
In the above example, a tuple object is define with initial string values. An item one and two will be assign to variable f1 and f2, the remaining elements converted to list and will be assigned to f3. The elements will be printed on console.
1 Item 1 : apple
2 Item 2 : banana
3 remaining : ['cherry', 'orange', 'kiwi']
Unpack first and last items
Unpack first and last items
1 tpl = ("apple", "banana", "cherry", "orange", "kiwi")
2
3
4 (f1, *f2, f3) = tpl
5
6 print("First item :", f1)
7 print("Remaining :", f2)
8 print("Last item :", f3)
1 First item : apple
2 Remaining : ['banana', 'cherry', 'orange']
3 Last item : kiwi
Unpack last items
Unpack last items from tuple
1 tpl = ("apple", "banana", "cherry", "orange", "kiwi")
2
3
4 (*f1, f2, f3) = tpl
5
6 print("Remaining :", f1)
7 print("2nd last :", f2)
8 print("Last item :", f3)
1 Remaining : ['apple', 'banana', 'cherry']
2 2nd last : orange
3 Last item : kiwi
Related options for your search