3) e. Tuples

From the first glance tuples might seem very similar to lists.

  • Like lists tuples are ordered sets.
  • Unlike lists tuples are immutable (can’t be changed).

That means that after you create a tuple you can only read its value and if you need to change it you will need to create a new one.

Because of that there is no reason to create an empty tuple if you want to populate it later. Instead you will have to declare a tuple literally by using parenthesis or use the tuple function to convert another iterable into a tuple.



So what can you do with a data structure that cannot be changed?

Similarly to lists you access tuple’s elements by their position.

1
2
Output:
Bob



If you try to change an element in a tuple then you will get an error. However, you can reassign all values to the tuple instead. That doesn’t really change the existing tuple but merely creates a new one with the same name. Here is an example to illustrate this:

1
2
Output:
(1, 3, 4, 5)

Methods:

index(e): Return the position of the first occurrence of e in tuple.

1
2
Output:
2




count(e): Return number of occurrences of e in tuple.

1
2
Output:
3




So yeah, there’s not a lot you can do with tuples. But that can be a good thing too.

Tuples are commonly used when a function needs to return multiple values.

1
2
3
4
5
6
7
8
def get_example_student():
    return ("Ray", "Morrison", 20)

student = get_example_student()

first_name = student[0]
last_name = student[1]
age = student[2]

In fact this kind of pattern is so common that Python allows us to simplify the syntax.

Isn’t that much simpler?