- Published on
8. lists and tuples in Python
- Authors
8. Please list a few differences between lists and tuples in Python.
Here's a concise comparison of lists and tuples in Python:
| Feature | List | Tuple |
|---|---|---|
| Mutability | ✅ Mutable (can be changed) | ❌ Immutable (cannot be changed) |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Methods | Has many methods like .append(), .remove(), .sort() | Fewer methods (no append, remove, etc.) |
| Performance | Slower (more overhead) | Faster (lightweight and fixed-size) |
| Use Cases | Best for dynamic collections | Best for fixed data or as dictionary keys |
| Can be a dict key? | ❌ No (not hashable) | ✅ Yes (if it contains only hashable items) |
Example:
# List (mutable)
my_list = [1, 2, 3]
my_list.append(4) # ✅ Works
# Tuple (immutable)
my_tuple = (1, 2, 3)
# my_tuple.append(4) ❌ Raises AttributeError
Summary:
- Use lists when you need to modify the collection.
- Use tuples when you want to protect data from changes or use them as keys in dictionaries.