Python Tuples

By

Learn how to use tuples in Python, the immutable and ordered data structure created with parentheses, including indexing, slicing, len(), sorted() and more.

~~~

Tuples are another fundamental Python data structure.

They allow you to create immutable groups of objects. This means that once a tuple is created, it can’t be modified. You can’t add or remove items.

They are created in a way similar to lists, but using parentheses instead of square brackets:

names = ("Roger", "Syd")

Why use a tuple instead of a list?

The immutability is the point. When a group of values should never change, like a pair of coordinates, a tuple says so in the code.

Tuples can also be used as dictionary keys, because they can’t change. Lists can’t do that.

Accessing items

A tuple is ordered, like a list, so you can get its values referencing an index value:

names[0] # "Roger"
names[1] # "Syd"

You can also use the index() method to find the position of a value:

names.index("Roger") # 0
names.index("Syd")   # 1

As with strings and lists, a negative index starts counting from the end:

names[-1] # "Syd"

You can count the items in a tuple with the len() function:

len(names) # 2

You can check if an item is contained into a tuple with the in operator:

print("Roger" in names) # True

You can also extract a part of a tuple, using slices:

names[0:2] # ('Roger', 'Syd')
names[1:]  # ('Syd',)

You can unpack a tuple into separate variables:

first, second = names
first  # "Roger"
second # "Syd"

Sorting and combining

You can create a sorted version of a tuple using the sorted() global function:

sorted(names) # ['Roger', 'Syd']

Notice the square brackets in the result: sorted() returns a list, not a tuple. The original tuple is untouched. If you need a tuple back, wrap the result in tuple().

You can create a new tuple from existing tuples using the + operator:

all_names = names + ("Vanille", "Tina")
# ('Roger', 'Syd', 'Vanille', 'Tina')

The single-item gotcha

To create a tuple with one item, you need a trailing comma:

dog = ("Roger",)

Without the comma, Python sees just a string wrapped in parentheses:

dog = ("Roger")
type(dog) # <class 'str'>

This bites when a function expects a tuple and you pass it a plain string by accident.

Trying to change a tuple

Assigning to an index raises an error:

names[0] = "Beau"
# TypeError: 'tuple' object does not support item assignment

If you find yourself needing to change the values, a tuple is the wrong structure, and you want a list. You can convert with list(names), modify it, and convert back with tuple() if needed.

Tagged: Python · All topics
~~~

Related posts about python: