Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the len() built-in function iterates through the collection to calculate its length, or does it access a collection's attribute? [duplicate]

Python has many built-in functions, and len() is one of them.

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

If collections and sequences are objects, they could hold a length attribute that can be updated every time something changes. Accessing this attribute would be a fast way to retrieve the collection's length.

Another approach is to iterate through the collection and count the number of items on the fly.

How does len() calculates said length? Through iteration or attribute access? One, none, both, other approaches?

like image 419
runw Avatar asked Mar 15 '15 04:03

runw


1 Answers

Python built-in collections cache the length in an attribute. Using len() will not iterate over all elements to count them, no.

Keeping the length as an attribute is cheap and easy to maintain. Given that the Python built-in collection types are used so widely, it'd be unwise for them not to do this.

Python built-in types with a length are typically built on top of the PyObject_VAR_HEAD struct, which includes an ob_size entry. The Py_SIZE macro can then be used to implement the object.__len__ method (e.g. the PySequenceMethods.sq_length slot in the C-API). See the listobject.c implementation for list_length for example.

like image 74
Martijn Pieters Avatar answered Sep 22 '22 21:09

Martijn Pieters