Python: how `len ()` is executed

Possible duplicate:
The cost of the len () function

How does Python calculate the length of a list (using the len() function)? Does it go through a for or while to do the same, or does it have an internal variable that stores the length of the list?

+6
source share
4 answers

Yes, CPython lists have an internal variable for length.

It is called ob_size ; all objects with a variable size have it.

+5
source

It uses an internal variable that stores the length of the list (like all other types of variable-length objects in Python). Thus, len () is an O (1) operation regardless of the size of the list (i.e., it works in constant time).

Here is the len () implementation for lists , here is the Py_SIZE macro , and here is the ob_size declaration that uses Py_SIZE.

+5
source
 a = range(10) b = range(1000000) timeit len(a) # 85.4 ns timeit len(b) # 94.4 ns 

This is not like a loop.

+4
source

In the python view, the len() function calls the __len__() class method, which returns the internally known length.

+3
source

Source: https://habr.com/ru/post/901280/


All Articles