Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of len() function

What is the cost of len() function for Python built-ins? (list/tuple/string/dictionary)

like image 778
Imran Avatar asked Jul 12 '09 04:07

Imran


People also ask

Is Len expensive Python?

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.

What is the time complexity of LEN ()?

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.

How does LEN () work in Python?

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.

Is Len () an inbuilt function?

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.


2 Answers

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.

like image 134
Alex Martelli Avatar answered Sep 19 '22 19:09

Alex Martelli


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

like image 45
James Thompson Avatar answered Sep 19 '22 19:09

James Thompson