What is the cost of len()
function for Python built-ins? (list/tuple/string/dictionary)
Python follows the idea that keeping the length as an attribute is cheap and easy to maintain. len() is actually a function that calls the method '__len__()'. This method is defined in the predefined classes of iterable data structures.
The runtime complexity of the len() function on your Python list is O(1). It takes constant runtime no matter how many elements are in the list. Why? Because the list object maintains an integer counter that increases and decreases as you add and remove list elements.
Python len() Function The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.
The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.
It's O(1) (constant time, not depending of actual length of the element - very fast) on every type you've mentioned, plus set
and others such as array.array
.
Calling len() on those data types is O(1) in CPython, the most common implementation of the Python language. Here's a link to a table that provides the algorithmic complexity of many different functions in CPython:
TimeComplexity Python Wiki Page
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