Q&A library Python

What is the difference between a tuple and a list in Python?

Python Beginner immutabilityliststuples

Short answer

A list is mutable and meant for a collection of similar items you may change. A tuple is immutable and often used for a fixed record of related values. Immutability lets tuples be dictionary keys.

The short version

A list uses square brackets and can be changed after creation. A tuple uses parentheses and cannot. Beyond that syntax, the convention is that lists hold a variable number of similar items, while tuples hold a fixed group of related values, like a coordinate. Because tuples are immutable, they can be used as dictionary keys and set members, which lists cannot.

The concrete difference

my_list = [1, 2, 3]
my_list[0] = 99        # fine, lists are mutable
my_list.append(4)      # fine

my_tuple = (1, 2, 3)
my_tuple[0] = 99       # TypeError: does not support item assignment

Trying to change a tuple raises an error, which is the whole point: it signals that the values are meant to stay fixed.

Why immutability is useful

Because a tuple cannot change, Python can use it wherever it needs something stable. Most importantly, tuples can be dictionary keys.

locations = {(51.5, -0.1): "somewhere", (53.8, -1.5): "elsewhere"}

A list cannot be a key, because its contents could change and break the dictionary's internal bookkeeping. So if you need a compound key, use a tuple.

The convention, not just the rule

Even when both would work, the choice signals intent. A list of orders says "a growing collection of the same kind of thing". A tuple (name, age, city) says "one record with a fixed set of fields in a known order". Following this convention makes code easier to read, because the container type hints at how the data is meant to be used.

The one-element gotcha

A single-element tuple needs a trailing comma, or the brackets are just grouping.

not_a_tuple = (5)     # this is the integer 5
a_tuple = (5,)        # this is a one-element tuple

Forgetting the comma is a classic bug that produces a plain value instead of a tuple.

Performance is a minor factor

Tuples are slightly smaller and faster to create than lists, but this is rarely a reason to choose one. Decide based on whether the data should be changeable, and let the small performance difference be a bonus rather than the deciding factor.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project