The len()
function is used to quickly and easily determine the number of elements in a list. This is particularly useful for looping over lists, performing validations, or managing list-based data. Here’s how it works:
len()
To find the length of a list, simply pass the list as an argument to len()
, which returns an integer value equal to the number of elements.
# Example list
numbers = [10, 20, 30, 40, 50]
# Get the length of the list
print(len(numbers)) # Output: 5
In this example, len(numbers)
returns 5
because there are five items in the list.
len()
You can use len()
to set limits for loops that iterate over lists:
# Print each element with its index
for i in range(len(numbers)):
print(f"Index {i}: {numbers[i]}")
len()
is also helpful for checking if a list is empty or has a specific number of elements.
# Check if a list is empty
if len(numbers) == 0:
print("The list is empty.")
else:
print("The list has elements.")
Alternatively, you can check for an empty list by directly evaluating the list in a conditional:
if not numbers:
print("The list is empty.")
len()
with Nested ListsFor lists containing other lists (nested lists), len()
returns the count of top-level elements only. To get the length of a nested list, you can access it individually and call len()
again:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(len(matrix)) # Output: 3 (three sublists)
print(len(matrix[0])) # Output: 3 (three elements in the first sublist)
len()
is the primary way to get the size of a list.len()
on individual sublists for nested sizes.