How to find length of a list in python?


A Python list data type can hold multiple different types of values in a single variable. It is a collection of ordered and changeable data items. A list in Python can have duplicate data items.

The given example shows a list in Python.

list1=['Python', 'programming', 2021]

For determining the length of a list, Python provides different ways for example you can use the Python len() function.

In this article, you will learn how to find the length of a list in Python.

Finding the length of a Python list using len() function

Python provides a built-in function called len() which can be used to determine the length of an object. This object could be a list, tuple, string, or dictionary, etc.

The syntax of this function is given below.

len(object)

This function will take one argument and return an integer that represents the size of the object.

For example –

See the given python code.

fruits = ['apple', 'banana', 'grapes', 'mango']

list_len = len(fruits)

print(f"The list has {list_len} elements.")

When you execute this code you will see the length of the given list.

Finding the length of a Python list using loop

This is one of the most basic ways to find the length of a list. In this method, we will declare a counter variable and initialize it with zero. We will loop through each item of the list and every time increment the counter variable.

In the end, the counter variable will have the size of the given list. Now see the given code.

fruits = ['apple', 'banana', 'grapes', 'mango']
counter = 0

for i in fruits:
  counter += 1

print(f"The list has {counter} elements.")

This will also display the length of the given list.

This method is not recommended because it requires extra lines of code.

Finding the length of a list using Python length_hint() function

This is another way to find the length of a list in Python. The length_hint() function is provided by the operator module. First, you need to import this module before you use this function.

The syntax of this function is given below.

length_hint(iterable)

Where iterable can be list, tuple, dict, etc.

You can see the example which is given below.

from operator import length_hint

fruits = ['apple', 'banana', 'grapes', 'mango']
list_len = length_hint(fruits)

print(f"The list has {list_len} elements.")

Executing this code will produce the given output.

Conclusion

From all the given methods the best approach is to use len() function because it is faster and comparatively easier than other methods.

If you have a query or feedback then please write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.