Sling Academy
Home/Python/Python: Counting the Number of Elements in a List (4 Examples)

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

Last updated: June 06, 2023

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

Next Article: Python: How to Check If a List Is Empty (3 Approaches)

Previous Article: Python: 6 Ways to Iterate Through a List (with Examples)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots