Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Just as list comprehensions use square brackets [] to construct lists, Python provides set comprehensions using curly braces {} to construct sets.
A set comprehension processes an iterable, applies optional filtering criteria, and automatically eliminates duplicate values, producing an unordered collection of unique elements with instant $O(1)$ hash-lookup capabilities.
+-------------------------------------------------------------------------------+
| SET COMPREHENSION REAL-WORLD ANALOGIES |
+-------------------------------------------------------------------------------+
1. THE WEDDING RECEPTION INVITATION AUDIT:
- Relatives from Lucknow, Kanpur, and Delhi send RSVP messages.
- The guest register receives duplicate entries:
["Sharma Family", "Verma Family", "Sharma Family", "Gupta Family"]
- The event planner runs a set comprehension:
unique_families = {family.strip() for family in rsvp_list}
- Duplicates are silently and automatically discarded, producing
the exact head-count of distinct families.
2. DELHI METRO SMART CARD COMMUTE HISTORY:
- Commuter swipes through 30 station turnstiles over a month:
swipes = ["Rajiv Chowk", "Hauz Khas", "Rajiv Chowk", "Noida City Centre"...]
- Extract distinct stations visited:
distinct_stops = {station for station in swipes}
- Yields the clean mathematical set of visited transit stations.
+-------------------------------------------------------------------------------+Because curly braces {} are shared between sets and dictionaries, Python distinguishes between them based on whether a colon (:) is present:
+---------------------------+-----------------------------------+-------------------------------------+
| COMPREHENSION TYPE | SYNTAX PATTERN | PRODUCED OBJECT |
+---------------------------+-----------------------------------+-------------------------------------+
| List Comprehension | `[x for x in seq]` | `list` (Ordered, allows duplicates) |
| Set Comprehension | `{x for x in seq}` | `set` (Unordered, unique values) |
| Dict Comprehension | `{k: v for k, v in seq}` | `dict` (Key-value mappings) |
| Generator Expression | `(x for x in seq)` | `generator` (Lazy stream) |
+---------------------------+-----------------------------------+-------------------------------------+Notice the vital distinction: {x for x in data} has no colon, so Python constructs a set.
Set comprehensions immediately resolve case-insensitivity and formatting anomalies:
Output:
You can add an if clause at the end to filter elements prior to insertion:
Output:
set([list comprehension])A common beginner mistake is wrapping a list comprehension inside a set() call:
Direct set comprehensions save memory by inserting directly into the set hash table without creating and destroying an intermediate list.
Output:
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
DO use {x for x in seq} directly instead of set([x for x in seq]). | DON'T expect set comprehensions to maintain sequence insertion order (sets are inherently unordered). |
| DO ensure items evaluated in set comprehensions are hashable (e.g. integers, strings, tuples). | DON'T attempt to put mutable lists or dictionaries inside set comprehensions (TypeError: unhashable type: 'list'). |
| DO use set comprehensions for fast $O(1)$ deduplication and membership lookups. | DON'T add a colon : unless you intend to build a dictionary comprehension. |
{expression for item in iterable if condition}.set([list_comp]).{k: v for ...}), it is a dictionary comprehension; if it has single values ({x for ...}), it is a set comprehension.If you forget to update your loop counter inside a while loop, the condition remains True forever:
Removing or inserting items in a list while looping over it causes skipped elements:
A. Square brackets [ and ] B. Parentheses ( and ) C. Curly braces { and } without key-value colons D. Angle brackets < and >
{x % 3 for x in range(10)}?A. 10 B. 3 C. 1 D. 0
A. SyntaxError: invalid syntax B. TypeError: unhashable type: 'list' C. ValueError: mutable object D. IndexError: list index out of range
A. Set comprehensions start with the keyword set B. Dictionary comprehensions contain a colon : separating key and value ({k: v for ...}), while set comprehensions contain only a single expression ({x for ...}) C. Set comprehensions must use parentheses inside the curly braces D. Dictionary comprehensions can only run on numbers
{word.lower() for word in words} better than set([word.lower() for word in words])?A. The set comprehension avoids allocating and subsequently garbage-collecting an intermediate list in memory B. set() is deprecated in Python 3.12 C. The set comprehension runs in parallel across all CPU cores D. set() cannot accept lowercase words
Build an automated security audit processor for an Indian cloud server gateway.
The server access log contains raw connection records with IP addresses, request protocols, and security inspection statuses ("ALLOWED", "SUSPICIOUS", or "BLOCKED").
"SUSPICIOUS" or "BLOCKED"."192.168." or "10.0." or "127.0.").ip in blacklist) operates in $O(1)$ constant time.In the next lesson, we will continue your Python learning journey with Project: Multiplication Table Generator (13: Loops).
👉 Continue to Next Lesson: Project: Multiplication Table Generator →
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| List Comprehension | Looping Techniques with enumerate() and zip() |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.