What is len in python?

The len is a built-in function in python. The len function returns the length (the number of items) of an object.

The syntax of len() function

len(seq)

One argument is required for the length function. The argument may be a sequence or collection

  • sequence – list, string, bytes, tuple, range
  • collection – dictionary, set

Raises error

The len function raises OverFlowError if the length is larger than sys.maxsize. The sys.maxsize is the maximum value of integer that can take

On 32 bit system, it is 231-1

On 64 bit system, it is 263 -1

How fast is len function in python?

The len function has a time complexity of O(1), which means the function is said to be constant time and does not depend on the size of the object.

The internal working of len function

Let’s look into the internal working of len function and understand what makes it faster. We can discuss this with an example, consider the following example code.

animals = ["dog","cat","mouse"]

print(dir(animals))

output

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

The dir() function returns the attributes and methods of any object. We list out all the attributes and methods of animals object (list). The __len__ attribute will count the items in the iterable object and the len function will access this attribute to get the length so it is independent of the size of the object. We can check this by following code

print(animals.__len__())
print(len(animals))

Output

3
3

Len examples in python

Examples of len function in python.

#strings
message = "hello world"
print(len(message))

#list
animals = ["dog","cat","mouse"]
print(len(animals))

#dict
tes = {'tom': 10, 'sape': 12}
print(len(tes ))

Output

11
3
2

Bonus – different ways to find the list length in python.

Conclusion

In conclusion, the len function is very useful in python programming.

Leave a Comment