← Back to Python, page 1

python-0001 · Easy fresher

How do lists and tuples differ in Python, and when would you choose each?

Lists are mutable sequences: items can be added, removed or replaced. Tuples are immutable once created, which makes them hashable when their items are hashable, so they can be dictionary keys or set members. Use a list for a collection that changes, and a tuple for a fixed group of values such as a coordinate or a record returned from a function.

Full answer
python
items = [1, 2]
items.append(3)
print(items)

point = (3, 4)
try:
    point[0] = 10
except TypeError as e:
    print("TypeError:", e)

distances = {point: 5.0}
print(distances[(3, 4)])
try:
    {[3, 4]: 5.0}
except TypeError as e:
    print("TypeError:", e)

Output:

text
[1, 2, 3]
TypeError: 'tuple' object does not support item assignment
5.0
TypeError: unhashable type: 'list'

The list grew in place, while the tuple raised a TypeError on assignment. Because the tuple of two numbers is hashable, it works as a dictionary key; a list in the same position raises TypeError: unhashable type: 'list'.

Other practical differences:

  • Tuples use slightly less memory and are created a little faster, which rarely matters but is a common interview point.
  • A tuple is only as immutable as its contents: ([1], 2) cannot be rebound item by item, but the inner list can still change, and such a tuple is not hashable.
  • Functions that return several values return a tuple, which callers unpack: lo, hi = min_max(data).
  • Named tuples (collections.namedtuple or typing.NamedTuple) add field names to fixed records.
python
items = [1, 2]
items.append(3)
print(items)

point = (3, 4)
try:
    point[0] = 10
except TypeError as e:
    print("TypeError:", e)

distances = {point: 5.0}
print(distances[(3, 4)])
try:
    {[3, 4]: 5.0}
except TypeError as e:
    print("TypeError:", e)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Lists are mutable, tuples immutable
  • Hashable tuples can be dict keys
  • Tuples suit fixed records
  • Immutability is shallow

Common mistakes

  • Assuming a tuple containing a list is fully immutable
  • Using a list as a dictionary key

Follow-ups

  • When would you use a NamedTuple instead of a dataclass?
  • Why is a one-item tuple written (x,)?

Tips

  • Show a tuple as a dict key