3 Easy Ways to Find the Length of a List in Python

Filed Under: Python
Length Of A Python List

In this article, we will be unveiling techniques to find the length of a Python list. Finding the length actually means fetching the count of data elements in an iterable.


Technique 1: The len() method to find the length of a list in Python

Python has got in-built method — len() to find the size of the list i.e. the length of the list.

The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.

Syntax:

len(list)

Example:

inp_lst = ['Python','Java','Kotlin','Machine Learning','Keras']
size = len(inp_lst)
print(size)

Output:

5

Technique 2: Using Python for loop to get the length

In order to find the length of the list in Python, using for loop is considered as a traditional technique or a naive method in the following manner:

  • Declare a counter variable and initialize it to zero.
  • Using a for loop, traverse through all the data elements and after encountering every element, increment the counter variable by 1.
  • Thus, the length of the array will be stored in the counter variable as the variable will represent the number of elements in the list.
counter = 0
for item in list:
 counter+=1
print(counter)

Example:

inp_lst = ['Python','Java','Kotlin','Machine Learning','Keras']
size = 0
print("Length of the input string:")
for x in inp_lst:
    size+=1
print(size)

Output:

Length of the input string:
5

Technique 3: The length_hint() function to get the length of the list

Python operator module has in-built length_hint() function to calculate the total number of elements in the list.

The operator.length_hint() method is used to find the length of an iterable such as list, tuple, dict, etc.

Syntax:

length_hint(iterable)

Example:

from operator import length_hint 
inp_lst = ['Python','Java','Kotlin','Machine Learning','Keras']
print("Length of the input string:")
size = length_hint(inp_lst)
print(size)

Output:

Length of the input string:
5

Best approach to find length of a Python list

Out of all the methods mentioned above, Python in-built len() method is considered as the best approach by programmers to get the size of the list.

Reason: The len() function requires O(1) time to calculate the size of the list because as list actually is an object so thus, it has memory space available to store the size.


Conclusion

Thus, in this article, we have understood the different ways to calculate the length of a Python list.


References

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages