Fundamentals 4 min read

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

This article shows four different Python techniques—using a lambda with filter, a list comprehension, the Counter class, and the built‑in count method—to count how many times the value 1 appears in a list, complete with code examples and explanations.

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

The author, a Python enthusiast, answers a fan's question about counting the occurrences of the number 1 in a list.

Implementation ideas

Several approaches are possible, such as using len(), list comprehensions, Counter, and the list count() method.

Methods

Method 1

Using an anonymous function (lambda) together with filter:

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

Method 2

Using 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 3

Using collections.Counter to obtain a dictionary of element frequencies:

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

Method 4

Using the list count method directly:

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

Conclusion

The article presents four concise Python solutions for counting the number of 1s in a list, illustrating the use of lambda + filter, list comprehension, Counter, and the built‑in count() method.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonLambdaCode ExamplesListlist-comprehensioncountingcollections.Counter
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.