Fundamentals 4 min read

Four Quick Python Tricks to Count the Number of 1s in a List

This article tackles a common Python question—how to count the number of 1s in a list—by presenting four concise solutions using filter with a lambda, list comprehensions, the Counter class, and the built‑in count method, each illustrated with clear code examples.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Four Quick Python Tricks to Count the Number of 1s in a List

The author, a Python enthusiast, addresses a fan's basic Python question about counting the number of 1s in an array.

Implementation Idea

The solution can use len(), list comprehensions, Counter, or the count() function.

Implementation

Method One

This method, contributed by a Beijing algorithm expert, uses an anonymous function and filter.

a = [1,0,2,0,1]
b = list(filter(lambda x: x==1, a))
print(b)
print(f"1的个数:{len(b)}")

Method Two

This method, from a Guangzhou data analysis expert, uses a list comprehension.

a = [1, 0, 2, 0, 1]
b = [x for x in a if x == 1]
print(len(b))
print(f"1的个数:{len(b)}")

Method Three

This method uses Counter to count each element and displays the result as a dictionary.

from collections import Counter
a = [1, 0, 2, 0, 1]
b = Counter(a)
print(b)

Method Four

This method uses the list count() method.

a = [1, 0, 2, 0, 1]
print(a.count(1))
print(f"1的个数:{a.count(1)}")

Conclusion

The article presents four different ways to count the occurrences of 1 in a list, demonstrating the use of anonymous functions, filter, list comprehensions, Counter, and count methods, helping the reader solve the basic problem.

PythontutorialCOUNTFilterlist-comprehensionCounter
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.