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?
len()
for
while
Yes, CPython lists have an internal variable for length.
It is called ob_size ; all objects with a variable size have it.
ob_size
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.
a = range(10) b = range(1000000) timeit len(a) # 85.4 ns timeit len(b) # 94.4 ns
This is not like a loop.
In the python view, the len() function calls the __len__() class method, which returns the internally known length.
__len__()
Source: https://habr.com/ru/post/901280/More articles:Add UIImage to CCSprite? - apiHow to display registry in TreeView in Delphi 7 - delphiHow to align in my image to move it vertically up (CSS, HTML)? - htmlA function definition inside another function definition: is it really? - cObjects in arrays do not collect garbage - garbage-collectionpreg_replace to delete offline numbers - phpHow to write a valid Decorator class in Python? - scopeConvert path to polygon - pythonHow to change the logo displayed in the browser title bar for a web application deployed to tomcat? - web-applicationsUsing column format in spec and blue book - openglAll Articles