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
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
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
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
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
What Are Set Comprehensions in Python?
Set comprehensions in Python provide a concise way to create sets using a single line of code. Similar to list and dictionary comprehensions, they allow you to generate sets by iterating over an iterable, optionally applying conditions.
A set comprehension consists of:
- An expression
- A
for
loop to iterate over an iterable - An optional
if
condition for filtering
Basic Syntax:
{expression for item in iterable}
Why Use Set Comprehensions?
- Conciseness: Reduces multiple lines of loop-based set creation into a single line.
- Readability: Makes code cleaner and easier to understand.
- Efficiency: Faster than traditional loops for generating sets.
- Automatic Uniqueness: Ensures all elements are unique (sets do not allow duplicates).
Simple Set Comprehension Examples
Example 1: Creating a Set from a List
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = {num for num in numbers}
print(unique_numbers)
Output:
{1, 2, 3, 4, 5}
Notice how duplicates are automatically removed.
Example 2: Generating Squares of Numbers
squares = {x**2 for x in range(1, 6)}
print(squares)
Output:
{1, 4, 9, 16, 25}
Adding Conditions in Set Comprehensions
You can include if
conditions to filter elements.
Example 3: Filtering Even Numbers Only
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = {num for num in numbers if num % 2 == 0}
print(even_numbers)
Output:
{2, 4, 6, 8}
Example 4: Using if-else Conditions
(Note: This requires modifying the expression itself since set comprehensions don’t directly support else
like dictionaries.)
numbers = [1, 2, 3, 4, 5]
modified_set = {num if num % 2 == 0 else num * 10 for num in numbers}
print(modified_set)
Output:
{10, 2, 30, 4, 50}
Nested Set Comprehensions
You can use nested loops inside set comprehensions.
Example 5: Creating a Set of All Possible Pairs
letters = {'a', 'b'}
numbers = {1, 2}
pairs = {(letter, num) for letter in letters for num in numbers}
print(pairs)
Output:
{('a', 1), ('a', 2), ('b', 1), ('b', 2)}
Set Comprehensions vs. For Loops
Traditional For Loop Approach:
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set()
for num in numbers:
unique_numbers.add(num)
print(unique_numbers)
Set Comprehension Approach:
unique_numbers = {num for num in numbers}
Advantages of Set Comprehension:
✔ Fewer lines of code
✔ More readable
✔ Faster execution
Practical Use Cases of Set Comprehensions
1. Removing Duplicates from a List
names = ["Alice", "Bob", "Alice", "Charlie", "Bob"]
unique_names = {name for name in names}
print(unique_names)
Output:
{'Alice', 'Bob', 'Charlie'}
2. Extracting Unique Characters from a String
text = "hello"
unique_chars = {char for char in text}
print(unique_chars)
Output:
{'h', 'e', 'l', 'o'}
3. Filtering Elements Based on a Condition
numbers = {10, 15, 20, 25, 30}
divisible_by_5 = {num for num in numbers if num % 5 == 0}
print(divisible_by_5)
Output:
{10, 15, 20, 25, 30}
Common Mistakes to Avoid
-
Confusing Sets with Lists/Dictionaries:
- Sets use
{}
but do not havekey:value
pairs like dictionaries. - Example:
❌{x: x*2 for x in range(3)}
→ This is a dictionary comprehension.
✅{x for x in range(3)}
→ Correct set comprehension.
- Sets use
-
Forgetting Sets Are Unordered:
- Unlike lists, sets do not maintain element order.
-
Using Mutable Elements:
- Sets can only contain immutable (hashable) elements.
- Example:
❌{[1, 2], [3, 4]}
→ Error (lists are mutable).
✅{(1, 2), (3, 4)}
→ Valid (tuples are immutable).
Conclusion
Set comprehensions are a powerful and efficient way to create sets in Python. They help in writing cleaner, faster, and more readable code while ensuring uniqueness of elements.
Key Takeaways:
✔ Use {expression for item in iterable}
for basic set creation.
✔ Add if
conditions to filter elements.
✔ Sets automatically remove duplicates.
✔ Prefer set comprehensions over loops for simplicity.