Python / Core Python Fundamentals Interview Questions
What is a tuple in Python and when should you choose it over a list?
A tuple is an ordered, immutable sequence. Once created it cannot be changed — no appending, inserting, or item reassignment. The syntax uses parentheses (optional in many contexts) or just a comma: point = 3, 4 is a tuple.
coords = (40.7128, -74.0060) # latitude, longitude x, y = coords # tuple unpacking print(x) # 40.7128 # Single-element tuple needs a trailing comma single = (42,) # tuple not_a_tuple = (42) # just the int 42 # Tuples support indexing and slicing like lists print(coords[0]) # 40.7128 print(coords[-1]) # -74.006
When should you choose a tuple over a list? Several rules of thumb:
- Immutability intent: if the data should not change after creation — RGB colour, (lat, lon), a database record — a tuple signals that clearly.
- Dictionary keys: only hashable (immutable) objects can be dict keys. A tuple of ints or strings is hashable; a list is not.
- Slight performance edge: tuples use less memory and are slightly faster to create than lists because Python can optimise their storage.
- Named tuples:
collections.namedtupleadds field names to a tuple for readability without the overhead of a full class:Point = namedtuple('Point', ['x', 'y']).
A common interview trap: tuples are immutable, but a tuple can contain a mutable object like a list. The tuple itself cannot be changed, but the list inside it can.
More Related questions...