How to find the length of a list in Python?

In this tutorial, we will learn how to find the length of a list in Python in various ways.

If you are used to basic programming in Python, you must be familiar with the concept of Python lists.
A Python list is a data type for storing sequences that allows you to store multiple items in a single variable.

Eg: eglist=[1,2,3,4,5]

example_list=[1,2,3,4,5]
print(example_list)
[1, 2, 3, 4, 5]

The length of a list is basically the number of items present in the Python list.
Eg: The length of the list above, i.e., example_list=[1,2,3,4,5] is 5 because it contains 5 items(elements).

There are 3 common ways to find the length of a list in Python. Let us look into each one of them in detail.

Using the len() function

The len() function accepts an iterable as an argument, counts the number of elements in the iterable list and returns the count value.
It is one of the most popular as well as conventional methods.

Syntax: len(iterable/listname)

Let us now look into an example for finding the length of the list using the len() method.

list1=["apple","banana","mango"]
listlen=len(list1)
print("the length of list1 is ", listlen)
the length of list1 is  3

Using the Naive Method

It is a very basic method that you can use in the absence of pre-defined simpler techniques. Here, we keep a counter and increase its value by running a loop until the last element of the list.

An example for the same is as follows:

list1=["apple","banana","mango"]
print("The list is:",list1)
counter=0
for i in list1:
    counter+=1
print("The length of the list is:", counter)
The list is: ['apple', 'banana', 'mango']
The length of the list is: 3

Using len_hint() method

The len_hint() method is a method defined in the operator class of Python that you can use to determine the length of the list.
An example of the same is shown below:

from operator import length_hint
list1=["apple","banana","mango"]
print("The list is:",list1)
listlen=length_hint(list1)
print("The length of the list is:", listlen)
The list is: ['apple', 'banana', 'mango']
The length of the list is: 3

Well, which one of the three is more efficient?

You can use the time function from the operator class to know which one of the above methods is the best. On finding the time taken to determine the length in each of the 3 classes, you will find that the time efficiency of len()>length_hint()>Naive method.

Leave a Reply

Your email address will not be published. Required fields are marked *