Sobes.tech
Middle

How are lists and tuples stored in Python memory?

sobes.tech AI

Answer from AI

Lists and tuples are stored as sequences of objects. The main difference is that tuples are immutable.

For lists:

  • Stored as a dynamic array of pointers to objects.
  • Size can change.

For tuples:

  • Stored as a static array of pointers to objects.
  • Size is fixed after creation.
# Example of a list
my_list = [1, 'hello', 3.14]
# In memory: a pointer to an array that stores pointers to 1, 'hello', 3.14
# Example of a tuple
my_tuple = (1, 'hello', 3.14)
# In memory: a pointer to an array that stores pointers to 1, 'hello', 3.14
# Difference from list: the size of the array cannot change
Attribute List (list) Tuple (tuple)
Mutability Mutable Immutable
Memory Dynamic array Static array
Read performance Faster for tuples due to fixed size Slightly slower
Write/delete performance Faster for lists Impossible (changing creates a new tuple)