Junior — Middle
What is the reason for the higher performance of tuples compared to lists?
sobes.tech AI
Answer from AI
Tuples in Python generally operate faster than lists for several reasons:
- Immutability: Tuples are immutable, which allows Python to optimize their storage and access.
- Less overhead: Tuples occupy less memory because they do not support methods related to changing their contents.
- Interpreter optimization: Due to their immutability, the interpreter can use more efficient internal structures for tuples.
Example:
import timeit
list_time = timeit.timeit("[1, 2, 3, 4, 5]", number=1000000)
tuple_time = timeit.timeit("(1, 2, 3, 4, 5)", number=1000000)
print(f"List creation time: {list_time}")
print(f"Tuple creation time: {tuple_time}")
As a result, creating and accessing tuples is usually faster than lists.