Part 2 of 6 · Chapter 2 of 4

Ordered Collections, Two Ways

Python gives you two ways to hold an ordered group of things, and the difference is not the brackets. Try to change a tuple the way you would a list, and read exactly what it refuses, and why.

Beginner9 min read

Python gives you two ways to hold an ordered group of things, and the difference is not the brackets. Try to change a tuple the way you would a list, and read exactly what it refuses, and why.

An ordered collection you can change

A list holds items in order, and you can add to it, remove from it, or replace an item at a position, all after it already exists.

Terminal
$ >>> fruit = ["apple", "banana"]$ >>> fruit.append("cherry")$ >>> fruit$ ['apple', 'banana', 'cherry']$ >>> fruit[0] = "avocado"$ >>> fruit$ ['avocado', 'banana', 'cherry']

The same idea, deliberately locked

A tuple looks almost identical — ordered, indexable, written with () instead of [] — except that once it is created, it cannot be changed at all.

The same action, on a list and a tuple

numbers = [1, 2, 3]

123

A list changes size in place.

numbers = (1, 2, 3)

123

A tuple never changes size.

Why the distinction is worth keeping

A tuple being locked is not a missing feature, it is the point. A function that returns a pair of coordinates, (x, y), returns a tuple on purpose — nothing downstream can accidentally reorder or extend it, because nothing downstream is allowed to touch it at all.

As a rule of thumb: reach for a tuple when the number of items is fixed by what the data is — a coordinate is always two numbers, a date is always three. Reach for a list when the number of items is expected to change while the program runs.

Key takeaways

  • Lists and tuples are both ordered — the difference is that a list can change size and contents, a tuple cannot.
  • A tuple being unchangeable is deliberate: it guarantees nothing downstream can alter what you handed it.
  • Use a tuple when the number of items is fixed by what the data is. Use a list when it is expected to grow or shrink.
  • A one-item tuple needs a trailing comma — (1,) — or Python does not treat it as a tuple at all.