Different Python Methods to Find the Length of a List

Python Len Method

To get the length of a list in Python, the most common way to do so is to use the len() method as it’s the most efficient and is a built-in function. Since a list is an object, the size of the list is already stored in memory for quick retrieval.

Using the len() Method to Get the Length of a List

You can use the built-in len() method to find the length of a list.

This len() method accepts a sequence or a collection as an argument and returns the number of elements present in the sequence or collection.

The Syntax of len() Is:

len(s)

Following example provides a list and uses the len() method to get the length of the list:

inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript']
size = len(inp_lst)
print(size)

Output
4

Alternative Ways to Find the Length of a List

Although the len() method is usually the best approach to get the length of a list because it’s the most efficient, there are a few other ways to find the length of a list in Python.

Using the length_hint() Method to Get the Length of a List

The Python operator module has a length_hint() method to estimate the length of a given iterable object. If the length is known, the length_hint() method returns the actual length. Otherwise, the length_hint() method returns an estimated length. For lists, the length is always known, so you would normally just use the len() method.

The Syntax of length_hint() Is:

length_hint(object)

The following example provides a list and uses the length_hint() method to get the length of the list:

from operator import length_hint 
inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript']
size = length_hint(inp_lst)
print(size)

Output
4

Using for Loop to Get the Length of a List

This section provides a less practical, but still informative, way of finding the length of a list with no special method. Using a python for loop to get the list length is also known as the naive method and can be adapted for use in almost any programming language.

The Basic Steps to Get the Length of a List Using a For Loop Are:

    • Declare a counter variable and initialize it to zero.

counter = 0

    • Use a for loop to traverse through all the data elements and, after encountering each element, increment the counter variable by 1.


for item in list:
counter += 1

The length of the array is stored in the counter variable and the variable represents the number of elements in the list. This variable can be used in other code or output.

print(counter)

Following example demonstrates how to get the length of a list:

inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript']
size = 0
for x in inp_lst:
    size += 1
print(size)

Output
4

Conclusion

In this article, you learned some different ways to find the length of a list in Python.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: