Tuples
In the last few lessons, we went into a lot of depth when discussing lists, membership operators and list methods. In this article we will discuss Tuples.
In simple terms, if multiple values are so related, that you will most likely use them together, use a Tuple.
The syntax for a tuple is similar to an array but instead of square braces, we use parantheses ( )
For example:
traits = ('tall', 'slim', 'blond') height = traits[0] build = traits[1] print(height, build)
>> tall slim
Tuples are Immutable
Previously, we discussed that lists are mutable ordered sequences of elements.
However, tuples are Immutable ordered sequences of elements. They are mainly used to store related information.
We can't add or remove elements from a tuple, without creating an entirely new variable.
Tuple unpacking
There is a more concise way to unpack tuples. Namely, you can use the comma notation ,
traits = ('tall', 'slim', 'blond') height build, hair = traits print(height, build, hair)
>> tall slim blond
This would respectively assign the variable to the corresponding tuple.