Middle
Why is accessing elements by index in Python fast?
sobes.tech AI
Answer from AI
Accessing elements by index in lists (list) and tuples (tuple) in Python is fast because these data structures are arrays with a fixed size of elements (or references to elements).
- Contiguous memory allocation: Elements of a list or tuple are stored in a contiguous block of memory.
- Direct access: The index of an element directly corresponds to the offset from the start of this memory block.
- Address calculation: The address of the desired element is calculated using the formula
base_address + index * element_size, wherebase_addressis the start address of the memory block,indexis the element's index, andelement_sizeis the size of one element (or the size of a pointer to an object if references are stored). - Time complexity: Such an indexing operation has a time complexity of O(1), meaning the access time does not depend on the size of the list or tuple.
Example:
# Creating a list
my_list = [10, 20, 30, 40, 50]
# Accessing the element at index 2
# Python quickly computes the address of the element by index
element = my_list[2]
Unlike lists and tuples, access to elements in data structures based on linked lists or unstructured data (e.g., set or dict by key) can take more time, as it requires either traversal (linked lists) or hash computation and collision resolution (dictionaries).