Kodeclik Blog


Finding the length of a Python list

A Python list can contain elements of many forms. It is often useful to find the length of a list and this blogpost shows the many ways to do it.

The hard way to find the length of a Python list

One way to find the length of a Python list is to use an iterator over the elements of a list and increment a counter as you go along.
For instance, consider the following code to count the number of months in a year.
The result is:

The easy way to find the length of a Python list

The easy way to find the length of a Python list is o use the len() method:
This also yields:

How fast is len() in calculating the length of a list?

It is said that len() takes constant time, i.e., O(1) time irrespective of the size of the list. This is because the internal list representation in Python stores the length details which can be readily retrieved using the len() method.
The len() method returns zero if the input list is empty.

Finding the length of a list of lists

Let us assume we are creating a list of lists and try to compute its length:
The result is:
Notice that the list contains three elements (which are lists themselves). len() is counting this number and thus returns 3. len() is NOT counting the elements in the flattened list of elements. To find this flattened sum, we can use a list comprehension approach:
The result is:

Finding list length using the __len__() method

The __len__() method is similar to the len() method in the way it is used although its syntax is slightly different:
The result is:
So what is the difference between len() and __len__()? First, note that len() is called like a function but __len__() is used like a method. Also len() is internally calling an object’s __len__() method and thus will return the same result.

Finding list length using the length_hint() function

Finally, there is a length_hint() function that you use similar to how you use len(). But you first have to import it from the operator library:
The result is as expected:
In this blog post you have learnt how to compute the length of a list and the many ways Python provides us ways to do it.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.