Hiprup

What is the difference between a list and a tuple?

Both list and tuple are ordered sequences of heterogeneous Python objects, but they differ in mutability, syntax, performance, and idiomatic intent.

Mutability — the primary difference:

  • List is mutable — you can append, extend, insert, remove, sort, reverse, or reassign elements in place.

  • Tuple is immutable — once created, its contents cannot be changed. (If a tuple contains a mutable object like a list, that inner object can still be mutated, but the tuple’s own references are fixed.)

Syntax:

lst = [1, 2, 3]        # list literal: square brackets
tup = (1, 2, 3)        # tuple literal: parentheses (optional)
one = (1,)             # single-element tuple NEEDS the trailing comma
also = 1, 2, 3         # comma, not parens, creates a tuple

Performance: tuples are slightly smaller and faster to construct and iterate because the interpreter can allocate a fixed-size object and skip mutation bookkeeping. The difference is modest but matters in tight loops and large data structures.

Hashability: a tuple of hashable items is itself hashable, so it can be a dict key or a set element; a list cannot.

d = { (x, y): "point" for x in range(3) for y in range(3) }  # OK
d = { [1, 2]: "nope" }  # TypeError: unhashable type: 'list'

Interview-ready summary: lists are mutable, variable-length sequences used for collections you modify; tuples are immutable, fixed-shape, hashable sequences used for records, keys, and return values. Reach for a tuple when the shape is fixed and you want safety or dict-key behavior; reach for a list when you need to change the sequence over time.

# List - mutable
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')        # OK
fruits[0] = 'avocado'        # OK
fruits.remove('banana')      # OK

# Tuple - immutable
coordinates = (10.5, 20.3)
# coordinates[0] = 15.0      # TypeError!
# coordinates.append(30.0)   # AttributeError!

# Tuple as dict key (hashable)
locations = {(40.7, -74.0): 'New York', (51.5, -0.1): 'London'}
# locations[[40.7, -74.0]] = 'NYC'  # TypeError! List not hashable

# Named tuple for clarity
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)  # 10 20

# Tuple unpacking
def get_user():
    return ('John', 30, 'john@email.com')  # Return tuple

name, age, email = get_user()  # Unpack

Lists support append, modification, and removal. Tuples reject any modification with TypeError.

Tuples can be dict keys because they are hashable; lists cannot. namedtuple adds readability with named fields. Tuple unpacking enables clean multiple return values from functions.

Key difference: mutability. Know that tuples are hashable (dict keys, set elements) and lists are not.

The memory/performance advantage of tuples and the namedtuple pattern show deeper knowledge.

What is the difference between a list and a tuple? | Hiprup