How to Find the Length of a List in Python

In Python, a list is a way to store multiple items in a single variable. For example, you might have a list of numbers, names, or even a mix of different types of data. Sometimes, you need to know how many items are in a list. This is called the length of the list.

Python makes it very easy to find the length using a built-in function called len(). Let’s go through this step by step.

Step 1: What is a List?

A list is a collection of items written inside square brackets []. Items are separated by commas.

numbers = [5, 10, 15, 20]

This list has 4 items: 5, 10, 15, and 20.

Step 2: Why Do We Need the Length of a List?

Knowing the length of a list is useful when:

  • You want to loop through all items.
  • You want to check if the list is empty.
  • You want to divide the list into parts.
  • You want to display the number of items to the user.

Step 3: Using the len() Function

Python provides a simple function called len() to count the number of items in a list.

Syntax:

len(list_name)
Example:
numbers = [5, 10, 15, 20]
print(len(numbers))
Output:
4
This means the list has 4 items.

Step 4: Storing the Length in a Variable

You can also store the result of len() in a variable if you want to use it later in your program.

Example:
fruits = [“apple”, “banana”, “cherry”]
count = len(fruits)
print(“There are”, count, “fruits in the list.”)

Output:
There are 3 fruits in the list.

Step 5: len() Works with Other Data Types Too

The len() Function is not just for lists. It also works with:

  • Strings – counts the number of characters
  • Tuples – count the number of items
  • Dictionaries – count the number of key-value pairs

Example:
len(“hello”) # Output: 5
len((1, 2, 3)) # Output: 3
len({“a”: 1, “b”: 2}) # Output: 2

Conclusion

This article introduced various methods to determine the length of a list in Python.

Find more information about how to check Python Version in Linux & Windows

Popular Posts You May Read

Explore more hosting insights, tips and industry updates.

How To Add New Users on cPanel

In this article, we’ll show you how to Create User Accounts on a cPanel Server.…

How to Manage Disk Space in Plesk Control Panel

How to Manage Disk Space in Plesk Control Panel

To manage disk space in Plesk is simple and ensures that resources are allocated efficiently.…

whats your policy on blacklisted servers? Can you give any guarantees that our server will not be on any blacklists?

Security and protection of the server has become one of the major issues for online…