Tuples¶
In addition to lists, Python provides another data type that can be used to store sequences of values. This second data type is called a tuple. In many ways, lists and tuples behave very similarly. Elements of a tuple each have an index, and are accessed in the same way as in a list. The fundamental distinction between the two data types is that tuples are immutable, meaning that once a tuple is created, it’s contents cannot be altered.
Syntactically, a tuple is define much in the same way as a list, except that parentheses ()
are used to define a tuple in place of the square brackets []
that are used for a list.
In the cell below, we define a tuple containing integer values.
my_tuple = (159, 348, 214, 381, 194)
We can access elements of a tuple in the same way as we would elements of a list.
print(my_tuple[0])
print(my_tuple[2])
print(my_tuple[-2])
159
214
381
Because of the immutability of tuples, we will get an error if we attempt to change the contents of an already created tuple.
my_tuple[1] = 999
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-7660b016544b> in <module>
----> 1 my_tuple[1] = 999
TypeError: 'tuple' object does not support item assignment
Although you cannot edit the contents of a tuple, you may reassign a new value to a variable that had contains a tuple. This is illustrated in the cell below.
my_tuple = 7
print(my_tuple)