Get List Length

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:

Basic Usage of 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.

Common Use Cases for len()

Looping with Length Check

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]}")
Conditionals and Validations

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.")
Using len() with Nested Lists

For 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)

    Summary

    • len() is the primary way to get the size of a list.
    • Use Cases: Useful for list validation, looping, and conditionals.
    • Nested Lists: Returns top-level length; call len() on individual sublists for nested sizes.