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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With