Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to find length of list in Python

Understanding Lists in Python

Before we jump into finding the length of a list in Python, let's break down the concept of a list. Imagine a shopping list. It's a collection of items you want to buy, like apples, bread, and milk. In Python, a list is similar. It's a collection of items, or in programming terms, elements. These elements could be numbers, strings, or even other lists.

# A simple list in Python
fruits = ['apple', 'banana', 'cherry', 'date']

How to Find the Length of a List

Python provides a built-in function called len() to find the length of a list. The term 'length' here refers to the number of elements in a list, similar to how you'd count the number of items on your shopping list.

Here's how you use the len() function:

fruits = ['apple', 'banana', 'cherry', 'date']
print(len(fruits))  # Output: 4

Unpacking the Len() Function

You might be wondering how the len() function works. Think of the len() function as a supermarket cashier. Just like how a cashier scans each item to total up your bill, the len() function "scans" through each element in the list, counts them up, and gives you the total.

Let's explore this with another example:

numbers = [1, 2, 3, 4, 5, 6]
print(len(numbers))  # Output: 6

As you can see, the len() function returns 6, which is the total number of elements in the list.

Length of Nested Lists

Things get a bit more interesting when we talk about nested lists. A nested list is a list within a list, sort of like a shopping list within another shopping list. For example, you might have a main shopping list, and within that list, you have a separate list for dairy products.

Here's an example of a nested list:

nested_list = ['apple', 'banana', ['milk', 'cheese', 'yogurt']]

If you use the len() function on this list, you'll get the output as 3. That's because Python counts the inner list ['milk', 'cheese', 'yogurt'] as one single element.

print(len(nested_list))  # Output: 3

If you want to find the length of the inner list, you can do so by using the len() function again on the inner list:

print(len(nested_list[2]))  # Output: 3

Conclusion: Length Matters, but Understanding Matters More

Congratulations! You've now learned how to find the length of a list in Python. Knowing the length of a list is a fundamental skill in Python programming, akin to knowing how many items you have in your shopping cart.

But remember, the number of items isn't always the most important thing. Sometimes, what matters more is understanding what those items are and how to use them effectively. In the same way, in Python, it's not just about knowing the length of your list. It's about understanding what the elements in your list represent and how you can manipulate them to get your desired output.

Now, armed with your len() function, you're ready to tackle even bigger Python challenges. Happy coding!