Tuples
Tuples vs Lists
When to use each
Interview: Tests understanding of data structure design and Python internals
Choosing between tuples and lists is a fundamental design decision in Python. While they share many operations, they serve different semantic purposes: tuples for heterogeneous, fixed data and lists for homogeneous, variable-length data.
Key Differences
- Mutability: Lists are mutable; tuples are immutable
- Semantics: Tuples represent records (like struct); lists represent collections
- Homogeneity: Tuples tend to be heterogeneous (different types); lists tend to be homogeneous
- Size: Tuples have fixed length; lists grow and shrink
- Hashability: Tuples (of immutables) can be dict keys; lists cannot
- Memory: Tuples use less memory (no overallocation buffer)
- Speed: Tuple creation is faster; iteration speed is similar
When to Use Tuples
- Fixed records: coordinates (x, y), RGB colors, database rows
- Dictionary keys: composite keys like (user_id, date)
- Function returns: returning multiple values
- Data integrity: when you want to prevent accidental modification
- Named tuples / typing.NamedTuple for lightweight record types
When to Use Lists
- Collections that change: append, remove, sort elements
- Homogeneous data: list of names, list of scores
- Stack/queue operations
- List comprehensions for data transformation
Rule of Thumb
If the data represents a record (fixed fields, different types) → tuple. If it represents a collection (variable length, same type) → list. Think of tuples as rows in a database and lists as columns.
Use Cases
Designing API return types (tuple for records, list for collections)
Choosing dict key types (tuple when composite key needed)
Performance-sensitive code where immutability is acceptable
Data modeling: records vs collections
Common Mistakes
Using lists for everything when tuples would be more appropriate (and vice versa)
Not knowing that tuples of immutable elements are hashable but tuples containing lists are not
Using tuples for collections that need to grow/shrink (converting to list and back is clunky)
Assuming tuples and lists are interchangeable — they have different semantic meanings in Python culture