Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : How `len()` is executed [duplicate]

Tags:

python

Possible Duplicate:
Cost of len() function

How Python calculates length of a list(using len() function )?Does it go through a for or while loop to do the same or it has some internal variable that stores the length of the list ?

like image 218
user1037114 Avatar asked Nov 11 '11 08:11

user1037114


2 Answers

Yes, CPython lists have an internal variable for the length.

It's called ob_size; all variable-sized objects have it.

like image 58
Petr Viktorin Avatar answered Oct 14 '22 14:10

Petr Viktorin


It uses an internal variable that stores the length of the list (as do all other variable-length object types in Python). So len() is an O(1) operation regardless of the size of the list (i.e. it runs in constant time).

Here's the implementation of len() for lists, here's the Py_SIZE macro it calls, and here's the declaration of ob_size that Py_SIZE uses.

like image 34
Simon Whitaker Avatar answered Oct 14 '22 15:10

Simon Whitaker