Fundamentals 8 min read

Discover Lucky Numbers in a List with a One‑Line Python Trick

This article explains the concept of “lucky numbers” in an integer list—where a number’s value equals its occurrence count—and walks through a Python solution that progressively uses set, count, map, zip, filter, lambda and sorted, culminating in a concise one‑liner implementation.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Discover Lucky Numbers in a List with a One‑Line Python Trick

Problem Definition

Given a list of integers, a "lucky number" is an element whose value equals its frequency in the list.

Step‑by‑step solution

1. Remove duplicates

Use a set to obtain the unique elements.

arr = [3,5,2,7,3,8,1,2,4,8,9,3]
unique = set(arr)  # {1,2,3,4,5,7,8,9}

2. Count occurrences

The list method count() returns the frequency of an element.

pairs = [(x, arr.count(x)) for x in unique]
# [(1,1), (2,2), (3,3), (4,1), (5,1), (7,1), (8,2), (9,1)]

3. Filter lucky numbers

Replace the explicit loop with map, zip and filter, then sort.

m = map(arr.count, unique)
z = zip(unique, m)
f = filter(lambda x: x[0] == x[1], z)
s = sorted(f, key=lambda x: x[0])
print('Lucky numbers are:', [item[0] for item in s])
# Lucky numbers are: [1, 2, 3]

4. One‑liner version

The whole logic can be expressed in a single statement.

print('Lucky numbers are:', [x for x in sorted(filter(lambda x: x[0]==x[1], zip(set(arr), map(arr.count, set(arr)))), key=lambda x:x[0])])
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.

algorithmLambdaMAPListfilterlucky numbers
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.