Difference between list and tuple in Python?
In Python, lists and tuples are both fundamental data structures used to store collections of items. While they share some similarities, such as being ordered sequences, they have critical differences primarily related to their mutability and intended use cases.
Key Differences
The most significant distinction between lists and tuples lies in their mutability. A mutable object can be changed after it is created, while an immutable object cannot. This characteristic influences how they are used and their performance implications.
Mutability
Lists are mutable, meaning you can modify their elements, add new elements, or remove existing ones after the list has been created. Tuples, on the other hand, are immutable. Once a tuple is created, its elements cannot be changed, added, or removed. This immutability makes tuples more predictable and safer for certain operations.
Syntax
Lists are defined by enclosing their elements in square brackets [], while tuples are defined by enclosing their elements in parentheses (). A tuple with a single element requires a trailing comma.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
single_element_tuple = (1,)
Operations and Methods
Due to their mutability, lists support a wider range of operations and methods for modification. Tuples have a more limited set of methods, primarily focused on querying elements.
- List methods:
append(),extend(),insert(),remove(),pop(),sort(),reverse(), etc. - Tuple methods:
count(),index().
my_list = [1, 2, 3]
my_list.append(4) # Valid
print(my_list) # Output: [1, 2, 3, 4]
my_tuple = (1, 2, 3)
# my_tuple.append(4) # This would raise an AttributeError
# Example of tuple immutability
# my_tuple[0] = 5 # This would raise a TypeError
Performance
Because tuples are immutable, Python can often optimize their creation and access, making them slightly faster than lists in some scenarios, especially when dealing with fixed collections of data. Tuples can also be used as dictionary keys because they are hashable (immutable), whereas lists cannot.
Summary Table
| Feature | List | Tuple |
|---|---|---|
| Mutability | Mutable (can be changed) | Immutable (cannot be changed) |
| Syntax | Square brackets `[]` | Parentheses `()` |
| Performance | Slightly slower | Slightly faster |
| Methods | Many (append, insert, pop, etc.) | Few (count, index) |
| Use Case | Collections that might change | Fixed collections, dictionary keys, function arguments |