Tuples#

A tuple in python is very similar to a list. Instead of using square brackets in the definition, 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 is that tuples are immutable, i.e., their contents cannot be changed.

# we can change values in the list
my_list[0] = 9999
my_list.append(8888)
print(my_list)
[9999, 24, 39, 45, 8888]
# we cannot change values in tuples
# the following results in errors
my_tuple[0] = 9999
my_tuple.append(8888)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [4], line 3
      1 # we cannot change values in tuples
      2 # the following results in errors
----> 3 my_tuple[0] = 9999
      4 my_tuple.append(8888)

TypeError: 'tuple' object does not support item assignment

We will not use tuples that often, but we will see them occasionally.