API Navigator Logo

Finding the Length of a Python List

Author: Newtum

This example shows how to get the number of items in a list using the built-in `len()` function in Python.

Using the `len()` Function

The `len()` function is a general-purpose Python function that returns the number of items in an object. When used with a list, it returns the total number of elements in that list.

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5, 6]
empty_list = []
mixed_list = [1, "hello", 3.14, True]

print(f"Length of fruits list: {len(fruits)}")
print(f"Length of numbers list: {len(numbers)}")
print(f"Length of empty list: {len(empty_list)}")
print(f"Length of mixed list: {len(mixed_list)}")

Practical Use Case: Looping

Knowing the length of a list is often useful for controlling loops or checking if a list is empty before performing an operation.

my_list = ["a", "b", "c"]

if len(my_list) > 0:
    print("The list is not empty.")
    print(f"The last item is: {my_list[len(my_list) - 1]}")
else:
    print("The list is empty.")