Lists in Python are used almost everywhere. In this tutorial we will look at four ways to find the length of a Python list: by using built‑in functions, recursion, and a loop. Knowing the length of a list is most often required to iterate through it and perform various operations on it.
len()
is a built‑in Python function for finding the length of a list. It takes one argument—the list itself—and returns an integer equal to the list’s length. The same function also works with other iterable objects, such as strings.
Country_list = ["The United States of America", "Cyprus", "Netherlands", "Germany"]
count = len(Country_list)
print("There are", count, "countries")
Output:
There are 4 countries
You can determine a list’s length in Python with a for
loop. The idea is to traverse the entire list while incrementing a counter by 1 on each iteration. Let’s wrap this in a separate function:
def list_length(list):
counter = 0
for i in list:
counter = counter + 1
return counter
Country_list = ["The United States of America", "Cyprus", "Netherlands", "Germany", "Japan"]
count = list_length(Country_list)
print("There are", count, "countries")
Output:
There are 5 countries
The same task can be solved with recursion:
def list_length_recursive(list):
if not list:
return 0
return 1 + list_length_recursive(list[1:])
Country_list = ["The United States of America", "Cyprus", "Netherlands","Germany", "Japan", "Poland"]
count = list_length_recursive(Country_list)
print("There are", count, "countries")
Output:
There are 6 countries
How it works. The function list_length_recursive()
receives a list as input.
list[1:]
, a slice of the original list starting from index 1 (i.e., the list without the element at index 0). The result of that call is added to 1. With each recursive step the returned value grows by one while the list shrinks by one element.The length_hint()
function lives in the operator module. That module contains functions analogous to Python’s internal operators: addition, subtraction, comparison, and so on. length_hint()
returns the length of iterable objects such as strings, tuples, dictionaries, and lists. It works similarly to len()
:
from operator import length_hint
Country_list = ["The United States of America", "Cyprus", "Netherlands","Germany", "Japan", "Poland", "Sweden"]
count = length_hint(Country_list)
print("There are", count, "countries")
Output:
There are 7 countries
Note that length_hint()
must be imported before use.
In this guide we covered four ways to determine the length of a list in Python. Under equal conditions the most efficient method is len()
. The other approaches are justified mainly when you are implementing custom classes similar to list.