List being an integral part of Python day-day programming has to be learned by all the python users and having a knowledge of its utility and operations is essential and always a plus. So this article discusses one such utility of finding the no. of elements in a list.
Method 1 : Naive Method
In this method one just runs a loop and increases the counter till the last element of the list to know its count. This is the most basic strategy that can be possibly employed in the absence of other present techniques.
Code #1 : Demonstrating finding length of list using Naive Method
The list is : [1, 4, 5, 7, 8] Length of list using naive method is : 5
Method 2 : Using
len() method offers the most used and easy way to find length of any list. This is the most conventional technique adopted by all the programmers today.
The length of list is: 4
The length of list is: 3
Method 3 : Using
This technique is lesser known technique of finding list length. This particular method is defined in operator class and it can also tell the no. of elements present in the list.
Code #2 : Demonstrating finding length of list using
The list is : [1, 4, 5, 7, 8] Length of list using len() is : 5 Length of list using length_hint() is : 5
Performance Analysis – Naive vs
When while choosing amongst alternatives its always necessary to have a valid reason why to chose one over another. This section does a time analysis of how much time it takes to execute all of them to offer a better choice to use.
Code #3 : Performance Analysis
The list is : [1, 4, 5, 7, 8] Time taken using naive method is : 2.6226043701171875e-06 Time taken using len() is : 1.1920928955078125e-06 Time taken using length_hint() is : 1.430511474609375e-06
Conclusion : It can be clearly seen that time taken is naive >>
length_hint() > len(), hence
len() is the best choice to use.
- Find length of a string in python (4 ways)
- Python | Find maximum length sub-list in a nested list
- Python | Ways to find indices of value in list
- Python | Ways to sum list of lists and return sum list
- Python | Ways to Convert a 3D list into a 2D list
- Python | Convert 1D list to 2D list of variable length
- Extending a list in Python (5 different ways)
- Python | Ways to rotate a list
- Python | Ways to Spilt the list by some value
- Python | Ways to flatten a 2D list
- Python | Ways to shuffle a list
- Different ways to clear a list in Python
- Python | Ways to remove particular list element
- Python | Multiply all numbers in the list (3 different ways)
- Python | Ways to remove duplicates from list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.