Script Valley
Python: Complete Language Course
Data StructuresLesson 2.2

Python tuples vs lists — when to use each

tuple creation, immutability, packing and unpacking, single-element tuple, tuple vs list performance, named use cases

Tuples

A tuple is an ordered, immutable sequence. Syntax uses parentheses (optional) or just commas. Once created, elements cannot be changed, added, or removed.

point = (3, 7)
rgb = (255, 128, 0)
coords = 10, 20   # parentheses optional

print(point[0])   # 3
print(len(rgb))   # 3

Unpacking

x, y = point            # x=3, y=7
a, b, c = rgb

# swap without a temp variable:
x, y = y, x

# ignore values with _:
first, _, third = (1, 2, 3)

Single-Element Tuple

not_a_tuple = (42)    # just an int
is_a_tuple  = (42,)   # trailing comma required

When to Use Each

Use tuples for data that should not change: coordinates, RGB values, database rows, function return pairs. Use lists when the collection will be modified. Tuples are slightly faster to iterate and use less memory. They are also hashable, so they can be used as dictionary keys — lists cannot.

Because tuples are immutable and hashable, they are safer for data that should not change: function return pairs, dictionary keys, and records from a database query. Python itself uses tuples extensively internally. When you return multiple values from a function, Python actually returns a tuple, and the unpacking syntax makes this transparent. Named tuples (collections.namedtuple or typing.NamedTuple) give you the safety of tuples with attribute access by name — a good upgrade when tuple index numbers make code unclear.

Up next

Python dictionaries — keys, values, and methods

Sign in to track progress