LESSON · 1 OF 5

What is a tuple

What is a tuple

A tuple is an ordered collection of values, just like a list, with one key difference: once you create it, you can't change it. Write one with parentheses and commas:

python
server = ("web-01", "10.0.0.5", 8080)

Like a list, a tuple keeps its order and can hold any mix of types. Here the tuple groups three related facts about one server into a single value.

Reading items

Access items by index with square brackets, exactly as you do with a list. Indexing starts at 0, and negative indexes count from the end:

python
server = ("web-01", "10.0.0.5", 8080)
print(server[0])    # web-01
print(server[-1])   # 8080

Slicing works too, and a slice of a tuple gives back a new tuple.

You can't change a tuple

Trying to assign to an item raises an error rather than changing anything:

python
server[2] = 9090
# TypeError: 'tuple' object does not support item assignment

There's no append, no remove, no pop. A tuple is fixed from the moment you create it.

The one-item gotcha

A single value in parentheses is not a tuple, it's just that value. The comma is what makes a tuple, so a one-item tuple needs a trailing comma:

python
not_a_tuple = ("web-01")     # just the string "web-01"
one_tuple = ("web-01",)      # a tuple with one item

You'll rarely write one-item tuples, but the trailing comma catches people off guard, so it's worth knowing why it's there.

Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute