Skip to content

7 min read

American Corners

Tuples and immutability

A group that should not change

A tuple is a sequence of values, much like a list, but written with round brackets instead of square ones:

location = (41.33, 19.82)

You read from it exactly as you read a list, by index:

print(location[0])   # 41.33
print(location[1])   # 19.82

The one big difference is in the name of this lesson: a tuple is immutable. Once it exists, you cannot append to it, delete from it, or reassign one of its slots. Trying to do location[0] = 42.0 does not quietly change the value; it raises an error and stops the program.

That sounds like a downside, but it is often exactly what you want. A pair of map coordinates, a red-green-blue colour, a date as year, month, day: these are single things made of parts that belong together and should travel as one. Making them unchangeable is a promise that no later line of code will pull them apart by accident.

Reading, and the one thing you cannot do

Everything you do to look at a list works on a tuple. You can index it, slice it, ask its length, and check membership:

week = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(len(week))         # 5
print(week[-1])          # Fri
print("Sat" in week)     # False

What you cannot do is any operation that would modify it. There is no .append(), and you cannot delete an item out of it. If you genuinely need a changed version, the honest move is to build a new one. A common trick is to convert to a list, edit that, and convert back:

week_list = list(week)
week_list[0] = "Monday"
week = tuple(week_list)

Notice you have not mutated the original tuple; you have replaced it with a fresh one. The old value never changed, which is the whole point.

Unpacking: pulling the parts back out

Tuples shine when you spread their parts across separate names in one line. This is called unpacking:

latitude, longitude = location
print("North:", latitude)
print("East:", longitude)

The number of names on the left must match the number of values on the right. This same move lets you assign several variables at once, and even swap two of them without a temporary variable:

a, b = 10, 20
a, b = b, a          # now a is 20 and b is 10

A worked example: returning more than one value

A function can only return one object, but if you make that object a tuple, you effectively hand back several results at once. Say you want both the area and the perimeter of a rectangle:

def rectangle_facts(width, height):
    area = width * height
    perimeter = 2 * (width + height)
    return area, perimeter

The return area, perimeter line quietly builds a tuple. At the call site you unpack it straight into two clear names:

a, p = rectangle_facts(4, 6)
print("Area:", a)          # Area: 24
print("Perimeter:", p)     # Perimeter: 20

This is why tuples turn up constantly even when you never type a bracket yourself: they are Python's natural way to say "here are a few values that go together".

Tip

Reach for a tuple when the collection has a fixed meaning where the position matters, like (day, month, year). Reach for a list when items come and go and the count can change. The shape you choose tells the next reader what to expect.

Prefer to see it explained? Here is the recorded Code for Albania lecture on this topic.

Try this now

Write a function sum_and_product(a, b) that returns both the sum and the product of the two numbers, with no brackets after return. Call it on 4 and 5, unpack the result into two names on a single line, and print each. You have just handed back two values through one return.

Check yourself

  1. What single thing can you do to a list that you cannot do to a tuple, and why is that restriction sometimes useful rather than annoying?
  2. A tuple is immutable, yet the "convert to list, change it, convert back" trick seems to change one. Explain what actually happens to the original tuple.
  3. A function ends with the line return name, age, city. Without any brackets, what type of object is handed back to the caller, and how would you receive all three values in one line?

Where this lesson comes from

Built from

  • Data Structures and Algorithms
  • Further reading: Brian Heinold, A Practical Introduction to Python Programming

alphaPlan courses are built from taught programmes rather than invented for the web. Where a claim rests on an outside standard or a reported case, it is named above so you can check it rather than take our word for it.

This course was developed by alphaPlan Center from programs delivered in partnership with the American Corners network.

Found something unclear, outdated or improvable? Suggest an improvement