When working with Python, you often need to determine the number of elements in a list. Suppose we have a list of fruit names:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
Now, we need to find out how many fruits are in this list.
The easiest and most common way to do this is by using the built-in len()
function. This function takes one argument – the list – and returns the number of elements in it.
Here is how it looks in practice:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
number_of_fruits = len(fruits)
print(number_of_fruits)
As a result of executing this code, the number 5 will be displayed – this is the number of elements in the fruit list.
Thus, the len()
function is a simple and convenient tool for determining the number of elements in a list in Python.