Is the len () function built into the collection to calculate its length or access the collection attribute?

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

Returns the length (number of elements) of an object. The argument can be a sequence (for example, a string, bytes, a tuple, list, or range) or a collection (for example, a dictionary, set, or frozen set).

If collections and sequences are objects, they can contain an attribute lengththat can be updated every time something changes. Accessing this attribute would be a quick way to get the length of the collection.

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

How does it len()calculate the specified length? Through iteration or access to attributes? One, none, both, other approaches?

+4
source share
1 answer

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

Saving length as an attribute is cheap and easy to maintain. Given that Python's built-in collection types are used so widely, it would be unwise for them not to.

Python PyObject_VAR_HEAD struct, ob_size. Py_SIZE object.__len__ (, PySequenceMethods.sq_length C-API). . listobject.c list_length, .

+6

All Articles