Length of the list in python

Python list is a useful data structure used to store more than one element. In this article, we will discuss various ways to find the length of a list in python.

We will discuss the following methods in detail and we will find out the faster method too.

  • Calculate the list length using the loop
  • Find length using the the len() function
  • The operator.length_hint() function

Find list length using loop

In this method, we will use a loop to find the length of the list.

Algorithm

  • Initialize list
  • Declare a counter variable and initialize it to zero
  • Loop through each element in the list
  • Increment counter by 1

Example

#initialize list
fruits_list = ["orange","apple","avocado","banana"]

#counter variable
counter = 0

for fruit in fruits_list:
     counter += 1

print( f"Length of the fruits list : {counter}")

Output

Length of the fruits list : 4

Find list length using the len() function

In this method, we will use the python built-in len() function to find the length of the list. This is the simplest way to find list length.

The len() function accepts an iterable argument and returns the length (the number of items) of an object.

Syntax

len(obj) 

Example

#initialize list
fruits_list = ["orange","apple","avocado","banana"]

#get length
length = len(fruits_list)

print( f"Length of the fruits list : {length}")

Output

Length of the fruits list : 4

Using the operator length_hint()

Finally, we can use the python operator module’s length_hint() function to calculate the length of the list.

The operator.length_hint() function can be used to calculate the length of iterable such as list, dict, tuples, etc.

Syntax

length_hint(iterable)

Example

#import operator
from operator import length_hint 

#initialize list
fruits_list = ["orange","apple","avocado","banana"]

#get length
length = length_hint(fruits_list)

print( f"Length of the fruits list : {length}")

Output

Length of the fruits list : 4

Which method is faster?

We can calculate the latency of each method with the help of the time function.

import time

#initialize list
fruits_list = ["orange","apple","avocado","banana"]

start= time.time()

#get length
length = len(fruits_list)

elapsed= time.time()- start

print( f"Elapsed time  : {elapsed}")
print( f"Length of the fruits list : {length}")

Similarly, we can find elapsed time in other methods too.

  • Loop method elapsed time: 0.0007174015045166016
  • The Len function elapsed time: 6.532669067382812e-05
  • The length_hint() elapsed time: 7.987022399902344e-05

From the above output, we can clearly see that the len() function is much faster than others.

Best method to find the list length

The len function is preferred by the programmers because it is faster than any other method. It has the time complexity of O(1).

Conclusion

In conclusion, we understood three different methods to find the length of the list.

Leave a Comment