While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
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.
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
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:
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
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
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.
Thus, in this article, we have understood the different ways to calculate the length of a Python list.
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Sign up