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:
1 |
len(list) |
Example:
1 2 3 |
inp_lst = ['Python','Java','Kotlin','Machine Learning','Keras'] size = len(inp_lst) print(size) |
Output:
1 2 |
<span style="color: #008000;"><strong>5 </strong></span> |
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.
1 2 3 4 |
counter = 0 for item in list: counter+=1 print(counter) |
Example:
1 2 3 4 5 6 |
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:
1 2 3 |
<span style="color: #008000;"><strong>Length of the input string: 5 </strong></span> |
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:
1 |
length_hint(iterable) |
Example:
1 2 3 4 5 |
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:
1 2 3 |
<span style="color: #008000;"><strong>Length of the input string: 5 </strong></span> |
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.