Tuples#
A tuple in python is very similar to a list. However, there are some important differences.
When defining a tuple, instead of using square brackets we use parentheses.
# this is a list
my_list = [11, 24, 39, 45]
# this is a tuple
my_tuple = (101, 172, 138, 450)
print(my_list)
print(my_tuple)
[11, 24, 39, 45]
(101, 172, 138, 450)
Elements in a tuple can be accessed/indexed just like lists:
print('The fourth element in the list is', my_list[3])
print('The fourth element in the tuple is', my_tuple[3])
The fourth element in the list is 45
The fourth element in the tuple is 450
The biggest difference between lists and tuples is that tuples are immutable, i.e., they cannot be modified/changed once they have been defined.
Notice how we can modify the contents of a list:
print(my_list)
# change the first element
my_list[0] = 99
# append a number to the end
my_list.append(8888)
print(my_list)
[11, 24, 39, 45]
[99, 24, 39, 45, 8888]
But we get an error if we try to do the same thing to a tuple:
my_tuple.append(8888)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[4], line 1
----> 1 my_tuple.append(8888)
AttributeError: 'tuple' object has no attribute 'append'
We will not use tuples that often, but we will see them occasionally.