What is the difference between list and tuple
In Python, lists and tuples are both used to store collections of items, but they have key differences:
Feature | List | Tuple |
---|---|---|
Mutability | Mutable (can be modified) | Immutable (cannot be modified) |
Syntax | Uses square brackets [ ] | Uses parentheses ( ) |
Performance | Slightly slower (dynamic size) | Faster (fixed size, optimized) |
Use Cases | Storing dynamic data collections | Storing fixed data (e.g., coordinates, configs) |
Methods | Supports append() , remove() , etc. | Fewer methods (immutable) |
Memory Usage | More memory (overhead for changes) | Less memory (fixed structure) |
Example:
# List (Mutable) my_list = [1, 2, 3] my_list[0] = 10 # Allowed # Tuple (Immutable) my_tuple = (1, 2, 3) my_tuple[0] = 10 # Error! (Tuples don't support item assignment)
When to Use Which?
Use a list when you need to modify, add, or remove items.
Use a tuple when the data should remain constant (e.g., dictionary keys, function arguments).