Tuples are much like lists in Python, for the little exception that they are inmutable, this means, once created you can’t make changes to it.
In order to create a Tuple you type the elements inside parenthesis ( … ) sepparated by a coma, just like lists.
>>>tuple=( 4, 5 , 7)
Hint: When you want to make a one element Tuple you should always put a coma after the element, this way Python won’t think that you only have an extra pair of parenthesis.
>>>tuple_1=(1,)
Since Tuples are inmutable, the methods used to modify them doesn’t exist; methods like append, remove, extend, etc. are no available for Tuples.
You can slice Tuples in order to create a new one that is a section of the one it is generated from. You can make a new Tuple from the slice of one like this:
>>>new_tuple=tuple[1:]
[ 5, 7]
And you can check if a value exists inside a Tuple the same way you do in Lists.
In this way we can check if a certain value exists inside a Tuple, if it exists it will return True, if it doesn’t it returns False
>>> 5 in tuple
True
>>> 9 in tuple
False
This way you can know the index of a certain value inside a Tuple, remember that this returns the index of the first apperance of the value.
>>>tuple.index(5)
1
Booleans of Tuples
As in Lists, Tuples have the same booleans. Whenever a Tuple has at least one element, whatever the element may contain, it will return True to a boolean expresion.
Asigning multiple values
One thing about Tuples that I tought was very interesting is the capacity to asign multiple values in one line. Her’es a little example:
>>>tuple=(5,4,6)
>>>(x, y, z) = tuple
>>> x
5
>>> y
4
>>> z
6
This is my #Mastery24 of my #TC1014