Program to find the length of list using Python

Introduction

In this section of python programming, we will find the length of the list or we can say that the number of elements in the list. Python provides in-built functions len() and length_hint() to directly find the length. Also we can use Naïve approach to find the length but when we go for the performance analysis and time complexities of the approaches, it is always better to go with the approach that takes less time to execute.

Naïve approach is nothing but traversing each elements in loop and increasing the counter until the last element is achieved.

 

Program to find the length of list using Python

Program

from operator import length_hint
import time


list = [2, 4, 1, 7]
# Find time taken by len()
start_len = time.time()
length_len = len(list)
end_len = str(time.time() - start_len)


# Find time taken by length_hint()
start_hint = time.time()
len_hint = length_hint(list)
end_hint = str(time.time() - start_hint)


print("Length of list using len()",length_len)
print("Length of list using length_hint()",len_hint)


print("Time taken by len()",end_len)
print("Time taken by length_hint",end_hint)

Output

Program to find the length of list using Python Output

Explanation

In the above code, to use the functions length_hint() and time() we have imported length_hint and time. Both the functions len() and length_hint() will be used to find the length of list but the difference lies in the time taken to execute the code. To calculate the time taken we have created start_* and end_* variable for both the functions. The end_* variable will return the time taken by the functions.

In the above output, we can observe that the time taken by len() < time taken by length_hint(). So it is advisable to consider the function which takes less time to execute. Similarly if we take the naïve approach in our account to compare the result will be;

Time taken, Naïve > length_hint() > len()

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.