Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Strings and String Manipulation
- Lists
- Tuples
- Dictionaries
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Dictionary Comprehensions
- Set Comprehensions
- Indexing and Slicing
- String Formatting
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Python Core Concepts
Python Collections
- Python collections ChainMap
- Python collections
- Python collections ChainMap<
- Python counters
- Python deque
- Python dictionary
- Python Lists
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Sets and Unordered Collections (set
) in Python
If you’ve ever needed to remove duplicates from a list, perform mathematical operations like union or intersection, or simply store a group of unique items, then Python sets are for you.
Sets are one of Python’s built-in data types and offer a simple, efficient way to handle unordered collections of unique elements. Whether you’re just starting out or brushing up on your knowledge, this guide will walk you through the ins and outs of Python sets in a friendly and easy-to-understand way.
Why Are Sets Important in Python?
Sets are crucial in scenarios where uniqueness and mathematical operations are required. Their importance lies in:
- Eliminating duplicates from sequences
- Performing set operations like union, intersection, and difference
- Offering fast membership testing
- Working well in mathematical logic, data science, and even algorithms
Prerequisites
Before diving in, you should be familiar with:
- Basic Python syntax
- Lists and tuples
- Looping and conditional statements
If you’ve worked with lists or dictionaries, understanding sets will be a breeze.
What This Guide Will Cover
- What is a Set in Python?
- Creating Sets
- Properties of Sets
- Accessing Set Elements
- Modifying Sets
- Set Operations (Union, Intersection, etc.)
- Set Methods Explained
- Frozen Sets
- Real-Life Use Cases
- Summary and Best Practices
1. What is a Set in Python?
A set is an unordered, mutable, and unindexed collection of unique elements. It is similar to sets in mathematics. Sets do not allow duplicates and do not maintain any order of elements.
Example:
my_set = {1, 2, 3, 4}
print(my_set)
# Output might be: {1, 2, 3, 4} or in a different order
2. Creating Sets
You can create a set using curly braces {}
or the set()
constructor.
Using Curly Braces
fruits = {"apple", "banana", "mango"}
Using set() Function
numbers = set([1, 2, 2, 3, 4])
print(numbers) # Output: {1, 2, 3, 4}
Note: Using
set()
on a list automatically removes duplicates.
3. Properties of Sets
Here are some key properties:
Property | Description |
---|---|
Unordered | Elements don’t maintain any order |
Unique items | No duplicate elements allowed |
Mutable | You can add/remove items |
Iterable | Can be looped through with a for loop |
4. Accessing Set Elements
Unlike lists or dictionaries, sets don’t support indexing or slicing because they are unordered.
Looping Through a Set
for fruit in fruits:
print(fruit)
Membership Test
print("apple" in fruits) # Output: True
print("grape" in fruits) # Output: False
5. Modifying Sets
Adding Elements
fruits.add("grape")
Adding Multiple Items
fruits.update(["kiwi", "orange"])
Removing Items
fruits.remove("banana") # Raises error if not found
fruits.discard("pineapple") # No error if not found
Clearing a Set
fruits.clear() # Empties the set
6. Set Operations
Python sets allow you to perform mathematical operations such as:
Union ( | or .union())
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Output: {1, 2, 3, 4, 5}
Intersection ( & or .intersection())
print(a & b) # Output: {3}
Difference ( - or .difference())
print(a - b) # Output: {1, 2}
Symmetric Difference ( ^ or .symmetric_difference())
print(a ^ b) # Output: {1, 2, 4, 5}
7. Set Methods Explained
Method | Description |
---|---|
.add(x) | Adds element x |
.update(iterable) | Adds multiple elements |
.remove(x) | Removes x , errors if not found |
.discard(x) | Removes x if found, no error otherwise |
.clear() | Empties the set |
.union(set2) | Combines two sets |
.intersection(set2) | Common elements |
.difference(set2) | Items in set1 not in set2 |
.symmetric_difference(set2) | Items not in both sets |
8. Frozen Sets
A frozenset is an immutable version of a set. Once created, it can’t be changed.
Example:
frozen = frozenset([1, 2, 3])
print(frozen)
# You can use it as a dictionary key or add it to another set
9. Real-Life Use Cases of Sets
1. Removing Duplicates
names = ["John", "Alice", "John", "Mike"]
unique_names = set(names)
print(unique_names)
2. Comparing User Roles
admin_roles = {"read", "write", "delete"}
user_roles = {"read", "write"}
print(admin_roles - user_roles) # Output: {'delete'}
3. Keyword Filtering
keywords = {"python", "data", "machine", "code"}
sentence = "Learn python and machine learning"
words = set(sentence.lower().split())
print(words & keywords) # Output: {'python', 'machine'}
4. Fast Membership Checks
banned_ips = {"192.168.1.1", "10.0.0.5"}
if user_ip in banned_ips:
print("Access Denied")
5. De-duplication in Logs
log_entries = ["error", "warn", "info", "error"]
unique_logs = set(log_entries)
print(unique_logs) # Output: {'error', 'warn', 'info'}
10. Summary and Best Practices
Python sets are incredibly handy when dealing with unique items or performing fast membership tests and mathematical operations.
Key Takeaways:
- Sets are unordered, unique, and mutable
- Great for de-duplication and mathematical comparisons
- Support rich set operations like union, intersection
frozenset
offers an immutable alternative- Useful in filtering, logging, and data processing
Best Practices:
✅ Use sets when you need uniqueness
✅ Prefer discard()
over remove()
to avoid errors
✅ Use set()
to remove duplicates from a list
✅ Consider frozenset
when you need immutable sets