Unpacking a Tuple
what is a Tuple ?
Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).
- according to official docs
In short, tuples are python Data Structure (similar to lists) that is used to store data of any kind, and they cannot be changed once created. They can also be faster than lists.
- Example of a tuple
ages = (10, 20, 30) # create a tuple by using the parenthesis, # lists are using a square bracket
to create a tuple of single value always add a comma after the value i.e: age = (10,)
Unpacking a tuple
Let's take the example above and say we want to give each age to three people.
long solution
ages = (10, 20, 30)
# assigning each value based on the index
john_age = ages[0]
jane_age = ages[1]
sally_age = ages[2]
print(john_age)
print(jane_age)
print(sally_age)
>>> 10
>>> 20
>>> 30
short solution
ages = (17, 21, 13)
# unpacking the tuple
john_age, jane_age, sally_age = ages
print(john_age)
print(jane_age)
print(sally_age)
>>> 17
>>> 21
>>> 13
See?? you get the same result in just one line. Three variables for the three tuple values
Bonus Resources
You can read more about tuple and how to create and manipulate them from the resources below. see you on the next one.
- Programiz tuple
- GeeksforGeeks Tuples in Python
- RealPython Lists and Tuples
- W3Schools Python Tuples