Explain Codes LogoExplain Codes Logo

Counting the number of True Booleans in a Python List

python
counting
list-comprehensions
numpy
Alex KataevbyAlex Kataev·Aug 16, 2024
TLDR

Here's the lucid solution to count True values in Python list using the sum() function:

count_true = sum(my_list)

With my_list = [True, False, True], the output is 2. In Python, sum() automatically treats **True as 1**, making the count of True a breeze!

Hopping on the sum() train with booleans

In Python, the simple yet powerful sum() function adds up elements. When you pass booleans to it, it serves as a clever method to count, since it interprets True as 1 and False as 0.

# Counting True elements via express train also known as sum() trues = [True, False, True, True] true_count = sum(trues) # All Aboard! Next stop: Count Town, Population: 3!

Taking the ‘list.count()’ route

If sum() is a train, then list.count() is a bus! It is more explicit and quite straightforward while counting occurrences of True:

true_count = trues.count(True) # Beep Beep, we got 3 True values onboard!

Clear as day, this explicit call makes the ride smoother for the Python rookies who might be mystified by sum().

Embracing the magic of list comprehensions

Lo and behold! Here comes the power of list comprehensions—ideal for times when direct identity check for True feels too mainstream:

true_count = sum(1 for x in trues if x)

This sorcery is particularly useful when you need to filter or apply conditions before counting, like picking special beans out of a magic beanstalk!

Pitfalls and pro-tips

Words of wisdom: abstain from redefining True and False. Remember, they are the immutable constants of the Python universe. Altering them could lead to some serious #PythonPitfalls.

When dealing with lengthy lists, sum() is your go-to choice for concise and efficient counting. But hey, don’t forget about list.count()! Powered by native C implementations, it might just edge past in a speed test.

Exploring more approaches to count

As a devout Pythonista, we should always be on the lookout for more options:

1. Harnessing the power of NumPy: For large datasets, or when you simply want to feel the sheer speed of lower-level code:

import numpy as np np_trues = np.array([True, False, True, True]) true_count = np.sum(np_trues) # I'm Lightning McQueen, I am speed!

2. Generator expression: More memory-friendly for huge lists, sparing the creation of an intermediate list.

true_count = sum(1 for item in huge_list if item) # I solemnly swear I am up to no good (memory)!

3. collections.Counter: Provides a count of all unique items in the list, in a neat little dictionary. Useful for when you are not just into True:

from collections import Counter true_count = Counter(huge_list)[True] # Counting: It's not just for True anymore!

Filtering: The detection game

Sometimes, you might need to filter out elements that don't meet a certain condition:

valid_treasures = [gold if gold > 0.5 else False for gold in dig_site] beeps = sum(valid_treasures) # Getting only the gold you're really after!

Here, gold > 0.5 represents a conditional True value scenario.