Python Sets, Dictionaries & Comparison of List, Tuple, and Set
In addition to sequential collections (str, list, tuple), Python provides two high-performance collections based on hashing: Set (for unique items) and Dictionary (for key-value pairs).
1. Set (set) in Python
A Set is an unordered, unindexed, and mutable collection of unique elements enclosed in curly braces { }.
Key Properties of Sets:
- No Duplicate Elements: Sets automatically remove duplicate values.
- Unordered & Unindexed: Elements do not have a fixed position, so you cannot access items using indexes like
s[0]. - Mutable: You can add or remove items from a set using
.add()and.remove().
Exam Trap — Empty Set Creation: Writing
s = {}creates an empty Dictionary, NOT an empty Set! To create an empty set, you must uses = set().
# Duplicate values are automatically removed
nums = {10, 20, 20, 30, 10, 40}
print(nums) # {10, 20, 30, 40}
# Adding and removing elements
nums.add(50)
nums.discard(20) # Removes 20 safely (does not raise error if 20 is missing)
Mathematical Set Operations in Python
Mathematical Set Operations (Let A = {1, 2, 3} and B = {3, 4, 5})
1. Union (A | B)
All unique elements from both sets:
{1, 2, 3, 4, 5}2. Intersection (A & B)
Only common elements in both sets:
{3}3. Difference (A - B)
Elements in A but NOT in B:
{1, 2}4. Symmetric Diff (A ^ B)
Elements in A or B, excluding common ones:
{1, 2, 4, 5}A = {1, 2, 3}
B = {3, 4, 5}
print("Union:", A | B) # or A.union(B) -> {1, 2, 3, 4, 5}
print("Intersection:", A & B) # or A.intersection(B) -> {3}
print("Difference (A - B):", A - B) # or A.difference(B) -> {1, 2}
print("Symmetric Diff:", A ^ B) # or A.symmetric_difference(B) -> {1, 2, 4, 5}
2. Dictionary (dict) in Python
A Dictionary is a mutable collection that stores data in key : value pairs enclosed within curly braces { }.
Key Properties of Dictionaries:
- Key-Value Mapping: Instead of numeric indexes (
0, 1, 2), items are accessed via their Key. - Unique & Immutable Keys: Keys must be unique and immutable (strings, numbers, or tuples). If you repeat a key, the new value overwrites the old value.
- Mutable Values: Values can be of any data type, can be duplicated, and can be modified anytime.
Creating, Accessing & Updating a Dictionary:
student = {
"roll_no": 101,
"name": "Ishita",
"course": "BCA",
"cgpa": 8.9
}
# Accessing values
print(student["name"]) # Output: Ishita
print(student.get("course")) # Output: BCA (Safer: returns None if key doesn't exist)
# Adding or updating a key-value pair
student["semester"] = 4 # Adds new key 'semester'
student["cgpa"] = 9.2 # Updates existing key 'cgpa'
# Iterating over a dictionary
for key, value in student.items():
print(f"{key} : {value}")
Important Built-in Dictionary Methods:
| Method | Description |
|---|---|
d.keys() |
Returns a view of all keys in the dictionary |
d.values() |
Returns a view of all values in the dictionary |
d.items() |
Returns a list-like view of (key, value) tuples |
d.get(key, default) |
Returns value for key without throwing KeyError if missing |
d.update(other_dict) |
Merges key-value pairs from another dictionary |
d.pop(key) |
Removes the specified key and returns its corresponding value |
d.clear() |
Removes all items from the dictionary |
3. Comparison of List, Tuple, Set, and Dictionary
This comparison table is one of the most frequently asked questions in DAVV BCA exams:
| Feature | List (list) |
Tuple (tuple) |
Set (set) |
Dictionary (dict) |
|---|---|---|---|---|
| Syntax / Brackets | Square brackets [ ] |
Parentheses ( ) |
Curly braces { } |
Curly braces {k: v} |
| Example | [10, 20, 30] |
(10, 20, 30) |
{10, 20, 30} |
{"id": 1, "name": "A"} |
| Mutability | Mutable (Changeable) | Immutable (Read-only) | Mutable (Changeable) | Mutable (Keys immutable) |
| Ordering | Ordered | Ordered | Unordered | Insertion Ordered (Python 3.7+) |
| Indexing / Slicing | Supported (L[0]) |
Supported (T[0]) |
Not Supported | Accessed by Key (D["id"]) |
| Duplicate Elements | Allowed | Allowed | Not Allowed (Unique only) | Keys: No, Values: Yes |
| Empty Creation | L = [] or list() |
T = () or tuple() |
S = set() (not {}) |
D = {} or dict() |
| Performance / Speed | Slower than Tuple | Faster & uses less memory | Very fast membership lookup (in) |
Very fast key lookup (O(1)) |
| Best Use Case | Dynamic collection of items that changes often | Fixed data records, coordinates, return values | Removing duplicates, mathematical set operations | Storing structured records (like JSON or student info) |