How to find the length of a list in Python?

How can I get the length of list Python to find the number of elements?

For example, if I have a list items = ["apple", "orange", "banana"], how can I find that there are 3 items in the list?

The simplest and most common way to get the length of a list in Python is to use the built-in len() function. For example, with items = ["apple", "orange", "banana"], you can find the length of list Python by calling len(items). This directly returns 3. It’s efficient, straightforward, and widely used.

Building on that, you can also calculate the length of list Python manually if needed. One way is to use a loop counter. For instance, initialize a counter to zero, iterate through each element in the list, and increment the counter for each element. While it’s not as efficient as len(), it gives you more control, especially if you want to combine the count with other custom logic. Here’s a quick example:

count = 0  
for item in items:  
    count += 1  
print(count)  # Output will be 3  

This manual method is helpful in scenarios where you’re doing more than just counting.

Those are great approaches! Another creative way to find the length of list Python is by using the sum() function with a list comprehension. This technique involves summing up 1 for every element in the list. For example:

length = sum(1 for _ in items)  
print(length)  # Output: 3  

While this isn’t as common as len() or even looping, it demonstrates the flexibility Python offers. It’s especially useful when you want to combine counting with a filtering condition, like counting only items that meet certain criteria.