
Tuples
A tuple object is similar to a list, but it cannot be changed. Tuples are immutable sequences, which means their values cannot be changed after initialization. You use a tuple to represent fixed collections of items:

Figure 2.17: A representation of a Python tuple with a positive index
For instance, you can define the weekdays using a list, as follows:
weekdays_list = ['Monday', 'Tuesday', 'Wednesday','Thursday','Friday','Saturday', 'Sunday']
However, this does not guarantee that the values will remain unchanged throughout its lifetime because a list is mutable. What we can do is to define it using a tuple, as shown in the following code:
weekdays_tuple = ('Monday', 'Tuesday', 'Wednesday','Thursday','Friday','Saturday', 'Sunday')
As tuples are immutable you can be certain that the values are consistent throughout the entire program and will not be modified accidentally or unintentionally. In Exercise 31, Exploring Tuple Properties in Our Shopping List, we will explore the different properties tuples provide a Python developer.
Exercise 31: Exploring Tuple Properties in Our Shopping List
In this exercise, you will learn about the different properties of a tuple:
- Open a Jupyter notebook.
- Type the following code in a new cell to initialize a new tuple, t:
t = ('bread', 'milk', 'eggs')
print(len(t))
You should get the following output:
3
Note
Remember, a tuple is immutable; therefore, we are unable to use the append method to add a new item to an existing tuple. You can't change the value of any existing tuple's elements, either because both of the following statements will raise an error.
- Now, as mentioned in the note, enter the following lines of code and observe the error:
t.append('apple')
t[2] = 'apple'
You should get the following output:
Figure 2.18: Errors occur when we try to modify the values of a tuple object
The only way to get around this is to create a new tuple by concatenating the existing tuple with other new items.
- Now use the following code to add two items, apple and orange, to our tuple, t. This will give us a new tuple. Take note that the existing t tuple remains unchanged:
print(t + ('apple', 'orange'))
print(t)
You should get the following output:
Figure 2.19: A concatenated tuple with new items
- Enter the following statements in a new cell and observe the output:
t_mixed = 'apple', True, 3
print(t_mixed)
t_shopping = ('apple',3), ('orange',2), ('banana',5)
print(t_shopping)
Tuples also support mixed types and nesting, just like lists and dictionaries. You can also declare a tuple without using parentheses, as shown in the code you entered in Step 5.
You should get the following output:
Figure 2.20: Nested and mixed items in a tuple