Skip to main content

How to find the length of a list in Python

How to find the length of a list in Python.

Here's a step-by-step tutorial on how to find the length of a list in Python:

  1. First, create a list that you want to find the length of. For example, let's create a list of numbers:
   numbers = [1, 2, 3, 4, 5]
  1. To find the length of the list, you can use the built-in len() function. This function returns the number of items in a list.
   length = len(numbers)
  1. Now, you can print the length of the list to see the result.
   print("The length of the list is:", length)

Output:

   The length of the list is: 5

Alternatively, you can directly print the length without assigning it to a variable:

   print("The length of the list is:", len(numbers))

Output:

   The length of the list is: 5
  1. If you have an empty list, the length will be zero. Let's create an empty list and find its length:
   empty_list = []
length = len(empty_list)
print("The length of the empty list is:", length)

Output:

   The length of the empty list is: 0
  1. You can also find the length of a list that contains different types of elements, not just numbers. For example, let's create a list of strings:
   strings = ["apple", "banana", "cherry"]
length = len(strings)
print("The length of the list of strings is:", length)

Output:

   The length of the list of strings is: 3
  1. It's worth noting that the len() function can also be used to find the length of other iterable objects, such as tuples and strings. Here's an example using a string:
   sentence = "Hello, World!"
length = len(sentence)
print("The length of the string is:", length)

Output:

   The length of the string is: 13

That's it! You now know how to find the length of a list in Python using the len() function.