Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
While lists and tuples are ordered sequences where duplicates are welcomed and positions matter, many software scenarios demand the exact opposite: an unordered collection where every element must be strictly unique and membership checks must execute at lightning speed.
In Python, a set is an unordered, unindexed, and mutable collection of unique, hashable objects enclosed in curly braces {...}. Sets eliminate duplicate entries automatically and leverage internal hash tables to deliver $O(1)$ constant-time membership lookups.
+-------------------------------------------------------------------------+
| PYTHON SETS REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------+
1. THE TOLL PLAZA FASTAG SCANNER (Instant O(1) Membership Check):
- When a vehicle drives through the Mumbai-Pune Expressway toll gate,
the RFID reader scans its FASTag ID.
- The toll computer does not search a linear list of 50 lakh cars one
by one (which would cause massive traffic jams).
- It checks an active database SET using a hash code in 0.001 seconds!
2. THE WEDDING INVITATION GUEST REGISTER (Deduplication):
- A host in Lucknow receives RSVP cards from relatives.
- Multiple family members might submit RSVP cards for "Sharma Niwas".
- The wedding planner notes down each unique household only once.
- Any duplicate submission is silently and automatically discarded!
3. THE CRITICAL EMPTY SET TRAP:
- Curly braces {} were historically reserved for empty dictionaries!
- Writing s = {} creates an empty DICT, NOT an empty set!
- To create an empty set, you MUST explicitly write s = set().
+-------------------------------------------------------------------------+Internally, Python sets are implemented using hash tables with open addressing. Each element's hash() value computes a direct memory bucket offset, allowing instant lookups regardless of whether the set contains 10 or 10,000,000 items.
Sets are initialized using curly braces {item1, item2} or the set() constructor:
The most common real-world use of set() is purging duplicate entries from an existing list:
Because sets calculate item positions via hash codes, every element in a set must be immutable and hashable. You cannot place a list, dictionary, or another set inside a set!
s[0]Because sets do not preserve sequence order, Python prohibits index-based access:
| Scenario | ❌ Anti-Pattern | ✅ Pythonic Idiom |
|---|---|---|
| Empty Set Creation | s = {} (Creates dictionary!) | s = set() |
| Remove List Duplicates | Writing a manual loop with if x not in seen: | clean = list(set(raw_list)) |
| Membership Lookup | Searching in a 100,000-item list ($O(n)$) | Searching in a 100,000-item set ($O(1)$) |
| Storing Sequences in Set | Storing lists {[1, 2], [3, 4]} (TypeError) | Storing tuples {(1, 2), (3, 4)} |
| Accessing by Index | s[0] (TypeError: not subscriptable) | Iterate with for or cast to list list(s)[0] |
+---------------------------------------------------------------------------+
| PYTHON SET PROPERTIES CHEAT SHEET |
+---------------------------------------------------------------------------+
| Property | Behavior / Rule |
|----------------------+----------------------------------------------------|
| Enclosure Syntax | Curly braces: {item1, item2} |
| Empty Set | set() <-- Mandatory! ({ } is an empty dict!) |
| Uniqueness | Strictly unique: Duplicates automatically removed |
| Ordering | Unordered (Arbitrary iteration sequence) |
| Indexing | Unindexed (Cannot write set[0]) |
| Element Constraint | Elements must be hashable/immutable (no lists/dicts)|
| Lookup Speed | O(1) constant time (Hash table buckets) |
+---------------------------------------------------------------------------+collection = {} in Python?A. An empty set of type set B. An empty dictionary of type dict C. A syntax error D. An empty tuple
len({"A", "B", "C", "A", "B"})?A. 5 B. 3 C. 2 D. TypeError
{"Python", [1, 2, 3]} raise a TypeError: unhashable type: 'list'?A. Sets cannot contain mixed data types B. Lists are mutable and therefore do not possess a fixed hash value required for set bucket indexing C. Sets only accept numbers D. Lists cannot be printed inside curly braces
s = {10, 20, 30}; print(s[0])?A. Prints 10 B. Prints a random element C. Raises TypeError: 'set' object is not subscriptable D. Prints None
x in my_set on a set containing 1,000,000 elements?A. $O(n)$ linear time B. $O(\log n)$ logarithmic time C. $O(1)$ average constant time D. $O(n^2)$ quadratic time
Build a web analytics module for an online store that logs incoming customer IP addresses during a festive Diwali sale. Purge duplicate hits from identical IP addresses, verify whether a suspected crawler bot IP is present using instant $O(1)$ lookup, and calculate unique conversion metrics.
In the next lesson, we will continue your Python learning journey with Adding & Removing Items (10: Sets).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Nested Tuples | Adding & Removing Items |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.