How to Find the Length of a List in Python

By 

Published on

2 min read

Python List Length

Lists are one of the most commonly used data types in Python and are used to store collections of items of the same type.

This article shows how to find the length of a list.

len() Function

Python has a built-in function len() that returns the length of a given object. The object can be a list , tuple, string, dictionary , etc.

The syntax of the len() function is as follows:

python
len(list)

The function accepts only one argument. The returned value is an integer that is the number of elements in the list.

Here is an example:

python
capitals = ['Tokyo', 'Sofia', 'London', 'Budapest']

list_len = len(capitals)

print("The list has {0} elements.".format(list_len))
output
The list has 4 elements.

Using Loop

Another way to get the length of a list is to use the for loop. This works by setting up a counter and looping through all the elements of the list. On each iteration, the current value of the counter variable is incremented by one.

Below is a sample code that shows how to find the number of elements in a given list using the for loop:

python
capitals = ['Tokyo', 'Sofia', 'London', 'Budapest']
counter = 0

for capital in capitals:
  counter = counter + 1

print("The list has {0} elements.".format(counter))
output
The list has 4 elements.

This method is not very Pythonic. You should always prefer using the len() function.

Conclusion

To find the length of a list in Python list, use the len() function.

If you have any questions or feedback, feel free to leave a comment.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page