Junior — Middle
Explain why a tuple in Python takes up less memory compared to a list.
sobes.tech AI
Answer from AI
Tuples in Python occupy less memory compared to lists because they are immutable data structures. This allows the interpreter to optimize their storage:
- Tuples do not require extra space for managing changes (e.g., for dynamic resizing).
- The internal structure of a tuple is simpler: there are no mechanisms for adding or removing elements.
- Lists are implemented as dynamic arrays with extra capacity, which requires additional memory for expansion.
Example:
import sys
lst = [1, 2, 3, 4]
tpl = (1, 2, 3, 4)
print(sys.getsizeof(lst)) # For example, 96
print(sys.getsizeof(tpl)) # For example, 80
It can be seen that a tuple takes up less bytes in memory because it does not store additional information for managing changes.