Python Set Comprehension
What is a Comprehension?
A comprehension is a compact way to build a collection from an iterable using a single expression.
Python has list, set, and dict comprehensions. A set comprehension looks like:
{ expression for item in iterable if condition } and it creates a set (unordered, unique values).
Comprehension एक कॉम्पैक्ट तरीका है जिससे किसी iterable से एक ही expression में नई collection बनाई जाती है।
Python में list, set, और dict comprehensions होते हैं। Set comprehension का रूप होता है:
{ expression for item in iterable if condition } जिससे एक set बनता है (unordered, unique values)।
When & Why to Use
- Deduplication: Quickly get unique values while transforming/filtering data.
- Readable one-liners: Replace small loops with clear, declarative expressions.
- Performance: Often faster than manual loops for constructing a set.
- Composability: Combine mapping + filtering + nested loops in one expression.
- डीडुप्लीकेशन: Transform/Filter करते समय unique values तुरंत पाएं।
- पढ़ने में आसान: छोटे loops की जगह साफ और संक्षिप्त one-liners लिखें।
- परफॉर्मेंस: सेट बनाने में अक्सर loops से तेज।
- कम्पोज़ेबिलिटी: एक ही expression में mapping + filtering + nested loops कर सकते हैं।
Advantages
- Concise syntax with built-in uniqueness of sets.
- Avoids intermediate containers in simple cases.
- Expresses intent (transform + filter to a set) directly.
- संक्षिप्त सिंटैक्स और set की built-in uniqueness।
- सरल मामलों में अतिरिक्त containers की ज़रूरत नहीं।
- इरादा स्पष्ट: (transform + filter) करके set चाहिए।
Best Practices & Pitfalls
- Keep expressions simple: If it gets long/complex, prefer a regular loop for readability.
- Only hashable elements: Sets can’t contain lists/dicts; use tuples instead (e.g.,
tuple(x)). - Order is not guaranteed: Sets are unordered; don’t rely on print order.
- Use conditions at the end:
{f(x) for x in data if cond(x)}is the usual readable pattern.
- Expression सरल रखें: बहुत complex हो तो readability के लिए सामान्य loop इस्तेमाल करें।
- सिर्फ hashable elements: Set में list/dict नहीं रख सकते; tuple का उपयोग करें (जैसे
tuple(x))। - Order fix नहीं: Set unordered है; print order पर भरोसा न करें।
- Condition अंत में रखें:
{f(x) for x in data if cond(x)}सामान्य व पठनीय पैटर्न है।
Example 1: Basic Squares
squares = {x*x for x in range(6)}
print(squares)
Create a set of squares using a simple set comprehension.
एक सरल set comprehension से squares का set बनाएं।
Output:आउटपुट:
Example 2: Filter Even Numbers
evens = {x for x in range(1, 11) if x % 2 == 0}
print(evens)
Filter only even numbers into the set.
सिर्फ even numbers को set में रखें।
Output:आउटपुट:
Example 3: Unique Uppercase Letters from a String
text = 'Hello World!'
letters = {ch.upper() for ch in text if ch.isalpha()}
print(letters)
Extract unique letters (uppercased) from a string.
String से unique letters (uppercase) निकालें।
Output:आउटपुट:
Example 4: Deduplicate with Transformation
names = ['Alice', 'alice', ' Bob ', 'BOB']
uniq = {n.strip().lower() for n in names}
print(uniq)
Clean and deduplicate names by trimming and lowering.
Trim और lowercase करके नामों को साफ व unique बनाएं।
Output:आउटपुट:
Example 5: From List of Tuples – Pick First Items
pairs = [(1, 'a'), (2, 'b'), (1, 'c')]
firsts = {x for x, _ in pairs}
print(firsts)
Build a set of unique first elements from pairs.
ट्यूपल pairs से पहले वाले unique elements का set बनाएं।
Output:आउटपुट:
Example 6: Nested Loops – Unique Sums
A, B = {1, 2}, {2, 3}
sums = {x + y for x in A for y in B}
print(sums)
Use nested loops inside a comprehension to get unique sums.
Nested loops का उपयोग करके unique sums पाएं।
Output:आउटपुट:
Example 7: Range Slicing with Condition
mid = {x for x in range(0, 21) if 5 <= x <= 10}
print(mid)
Select numbers in a specific interval.
एक खास रेंज के numbers चुनें।
Output:आउटपुट:
Example 8: Unique Word Lengths
sentence = 'sets are great for unique things'
lengths = {len(w) for w in sentence.split()}
print(lengths)
Collect unique word lengths from a sentence.
Sentence से शब्दों की unique लंबाइयाँ लें।
Output:आउटपुट:
Example 9: From Dict – Keys with High Scores
scores = {'Ann': 91, 'Bob': 85, 'Cara': 95}
high = {name for name, sc in scores.items() if sc >= 90}
print(high)
Pick keys from a dict based on a value condition.
Value condition के आधार पर dict से keys चुनें।
Output:आउटपुट:
Example 10: Make Hashable from Unhashable
lists = [[1, 2], [1, 2], [2, 3]]
uniq_tuples = {tuple(x) for x in lists}
print(uniq_tuples)
Convert lists to tuples to store in a set.
Set में रखने के लिए lists को tuples में बदलें।
Output:आउटपुट:
Example 11: Avoid Booleans as Accidental Results
data = [0, 1, 2, 3]
# Bad: {x > 1 for x in data} -> {False, True}
filtered = {x for x in data if x > 1}
print(filtered)
Put the condition at the end to filter, not as the expression.
Filter के लिए condition अंत में रखें, expression में नहीं।
Output:आउटपुट:
Example 12: Compare with set(map(...))
nums = [1, 2, 3, 4]
comp = {x*x for x in nums}
via_map = set(map(lambda x: x*x, nums))
print(comp == via_map)
print(comp)
Set comprehension is often clearer than set(map(...)).
अक्सर set(map(...)) से set comprehension ज़्यादा स्पष्ट होता है।
Output:आउटपुट:
{1, 4, 9, 16}