Beginner Python tutorial – 11 – Tuples

Tuples are just another data structure we can use to store multiple objects or values. Until now, we only used List. Let’s have a look into them!

What are Tuples?

Tuples are a data structure, similar to List, that can hold two or more values or objects. But there are a few differences.

For example, on Tuple creation, we use ‘(‘ and ‘)’ instead of brackets:

my_list = [3, 56, 6, 7, 2,67] # This creates a list

my_tuple = (5, 7, 2, 8, 23, 8, 12, 5) # This creates a tuple

But the most important difference is that a Tuple is immutable. Once set, you can’t modify it. You can’t add, subtract or replace it:

my_tuple = (5, 7, 2, 8, 23, 8, 12, 5)

my_tuple[0] = 34
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-e4bd97e7e8db> in <module>
----> 1 my_tuple[0] = 34

TypeError: 'tuple' object does not support item assignment

Why do we want a list of elements we can’t modify? Good question.

User cases for tuples

Seems like Tuple is more limited than List. We can’t not modify it!

Well, as you say, we can’t modify them. And why we should? Sometimes we need to offer a list of elements we don’t want to modify. Think of the days of the week. I don’t think we are going to add or remove days of the week anytime soon, so create a Tuple for the days of the week is better than a List. We don’t want to let the user modify it.

And of course, you and I as programmers, we shouldn’t modify them by accident.

Another case we want to use Tuple is when the order is important.

In the last example, the days of the week, we don’t want to modify the Tuple, removing a random day by accident. But we don’t want to lose the order.

Imagine we are creating a videogame and we want to give the user the option to select 2 paths: To the left or to the right. With Tuple, we know that we will display first the ‘Left’ option and second the ‘Right’ option, as we typed it.

But also Tuple is faster than List. Tuple uses less memory, so creating a Tuple is faster than List as it involves fewer steps. See this test I did with the ‘dis’ module:

tuples vs list
tuples uses fewer steps on creation, compared to lists

Tuple methods

Tuple has only two methods: index and count. And you can guess what they do.

Even better, let’s see it.

count()

‘count’ counts how many times the Tuple contains the element of the argument. We have a Tuple and we want to know how many times the ‘admin’ logged in today:

today_log = ('admin', 'joey12', 'sarah_87', 'admin', 'yugioh_master2004', 'admin')
today_log.count('admin')
> 3

As you can see, we don’t need to create a for loop to count how many times an element is in a Tuple . count() method figures it out.

index()

Index returns the first position of the argument passed down.

today_log = ('admin', 'joey12', 'sarah_87', 'admin', 'yugioh_master2004', 'admin')
today_log.index('sarah_87') # It should return 2 (as 'sarah_87' is the third element and we start counting from 0)
> 2

today_log[2]
>'sarah_87'

today_log.index('David') # It should return a ValueError as the value is not in the tuple
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-b9e884188095> in <module>
----> 1 today_log.index('David')

ValueError: tuple.index(x): x not in tuple

If the element is in the Tuple, we’ll get the position of the element in the Tuple . If it doesn’t exist, we’ll get an error.

Mutate the immutable

Remember I said that Tuple is immutable? Well, I was right. You can’t.

But you can. Really.

You can’t mutate the Tuple, as we don’t have ‘append’ or ‘remove’ methods as we have in List. But we can change the value. Not by modifying it, but by assigning it a new value. And that new value can be almost the same as the one we had initially.

# We create a tuple by assigning it a few elements, just to change the value to '3'
today_log = ('admin', 'joey12', 'sarah_87', 'admin', 'yugioh_master2004', 'admin')
today_log = 3
today_log
> 3

# We create a tuple by assigning it a few elements, just to replace the value to the same tuple without the last element with slicing
today_log = ('admin', 'joey12', 'sarah_87', 'admin', 'yugioh_master2004', 'admin')
today_log = today_log[0:-1] # Using slicing, we remove the last one
today_log
> ('admin', 'joey12', 'sarah_87', 'admin', 'yugioh_master2004')

As you see, are not using Tuple methods to change its value (as those methods don’t exist). But we can assign new values. On the second example, we are using slicing to assign all the values the tuple had but the last one. We are emulating the ‘pop’ method that List has.

Summary

So, Tuple is ‘list-like’ data structures with the disadvantage that we can’t modify them.

But is that a disadvantage? Sometimes we just want a closed list of elements we don’t want to modify. If we want to get a list of all our customer’s email, we don’t want to modify them, so we should use a Tuple instead. Or when the order is important.

We can also locate easily the order of an element with .index() method, and .count() how many times an element is in a List

Challenge time

Let’s have a few exercises to interiorise today’s lesson

Challenge 1: Get the index of a value

We have a tuple. Find what is the position of ‘Python’ within the tuple.

programming_languages = ('Rust', 'Javascript', 'C#', 'Python', 'Dart')

Challenge 2: Count how many times we are ‘rinsing’

Print how many times we are rinsing in this process

hair_care_instructions = ('rinse', 'repeat', 'rinse', 'repeat', 'rinse', 'repeat', 'rinse', 'repeat', 'rinse', 'repeat', 'breath', 'rinse', 'repeat', 'rinse', 'repeat', 'stop')

Challenge 3: Remove an element from a tuple by index

We are buying too much groceries. Remove the 4th element.

groceries = ('lemon', 'orange', 'water', 'pasta', 'ice cream', 'more ice cream', 'pizza')

Challenge 4: Remove an element from a tuple by string

We have gone crazy and we don’t want to learn Python anymore! Create a function that removes ‘Python’ from the programming languages tuple.

Remember that tuples are immutables. Almost. Check the lesson again to learn how you can do it.

programming_languages = ('Rust', 'Javascript', 'C#', 'Python', 'Dart')

Yes, I know the 3 and the 4 challenges are hard. Remember that we can use slicing and other tools. We are not limited to only the Tuple methods.

If you compare your result with mine here.

Next lesson: 12 – Sets

Follow me on Twitter: https://twitter.com/DavidMM1707

My GitHub: https://github.com/david1707