Sobes.tech
Middle

Why can a Python list store elements of different types and still work with fast index access?

sobes.tech AI

Answer from AI

In Python, a list (list) is implemented as a dynamic array that stores not the objects themselves, but references (pointers) to the objects. Thanks to this, a list can contain elements of different types — each element simply points to an object of the corresponding type.

Index access is fast (O(1)) because the list is an array of pointers, and you can instantly get the address of the needed object by index. The object itself can be anywhere in memory, but the reference to it is stored consecutively in the array, ensuring quick indexing.

Example:

lst = [123, 'abc', 3.14, [1, 2, 3]]
print(lst[1])  # 'abc'

Here, lst contains references to objects of different types: int, str, float, list.

Why can a Python list store elements of different… - sobes.tech