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.

MS SQL Server Data Types: A Helpful Guide for Developers

MS SQL Server Data Types: A Helpful Guide for Developers

Once you know how data is actually stored, working with databases becomes a lot easier.…

Incorrect login-Horde / Squirrelmail IMAP problem

The problem for incorrect login for Horde webmail OR the IMAP problem for Squirrelmail is…

How to Install Updates on an Unmanaged Server

In this article, we will illustrate the process of updating an unmanaged server. Keeping your…