Python: Counting the Number of Elements in a List (4 Examples)

Updated: June 6, 2023 By: Goodman Post a comment

This quick article shows you how to count the number of elements in a list in Python.

Using the len() function

The built-in len() function takes a list as an argument and returns an integer value that represents the length of the list (or the number of its elements).

Example:

my_list = ["hello", "slingacademy.com", 123, None, True, False]
length = len(my_list)
print(f"Length of my_list is {length}")

Output:

Length of my_list is 6

The len() function is the easiest and most common way to get the length of a list in Python. Its syntax is concise, and it works efficiently.

Ignoring None when counting elements in a list

The len() function does not check the value or type of the elements in the list, it only counts how many elements there are. Therefore, None elements are considered valid elements and are included in the length of the list.

If you want to ignore None elements when counting the elements in a list, chose one of the following approaches to go with.

Using list comprehension

You can use list comprehension to create a new list that contains only the non-None elements of the original list and then use the len() function to get its length.

Example:

my_list = ["Sling", None, "Academy", None, "dot com"]

# create a new list with non-None elements
non_none_lst = [x for x in my_list if x is not None] 

# get the length of the new list
length = len(non_none_lst) 

# print the length
print(length) 

Output:

3

Using the sum() function

You can use the sum() function to add up the number of non-None elements in the original list by using a generator expression that returns 1 for each non-None element and 0 for each None element.

Example:

mixed_list = ["turtle", None, "tortoise", None, "wolf"]

# sum up the number of non-None elements
count = sum(1 for x in mixed_list if x is not None) 

# print the result
print(count)

Output:

3

Using a for loop and a counter variable

What we’ll do is Iterating over the list using a for loop and increment a counter variable in each iteration if the element is not None.

Example:

# Creating a list
my_list = [1, 2, 3, 4, 5, None, 6, None]

# Counting the number of not-None elements
count = 0
for element in my_list:
    if element is not None:
        count += 1

# Printing the count
print(count)

Output:

6