Comprehensions
-
Write shorter and more readable Python code using list, set, and dictionary comprehensions.
What are Comprehensions?
Comprehensions provide a short and readable way to create collections (list, dictionary, set) from existing data.
👉 They replace long for loops with one-line expressions.
Why We Use Comprehensions
Less Code – write in one line
Better Readability – clean and clear
Faster Execution – optimized internally
Easy Data Filtering – with conditions
Used in Real Projects – data processing, filtering, transformation
Real-Life Analogy
Normal Loop → Writing attendance one by one
Comprehension → Automatic attendance report generation
1.List Comprehension
What is List Comprehension?
A list comprehension creates a list using a single line of code.
Syntax
new_list = [expression for item in iterable if condition]
Simple List Comprehension
This example creates a list of squares.
squares = [x * x for x in range(1, 6)]
print(squares)
Generate roll numbers automatically
roll_numbers = [roll for roll in range(1, 11)]
List Comprehension with Condition
This example filters even numbers from a list.
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
2.Dictionary Comprehension
What is Dictionary Comprehension?
A dictionary comprehension creates a dictionary in one line.
Syntax
new_dict = {key: value for item in iterable if condition}
Simple Dictionary Comprehension
This example creates a dictionary of numbers and their squares.
square_dict = {x: x * x for x in range(1, 6)}
print(square_dict)
Real-Life Example
Student roll number and marks
students = {1: 85, 2: 90, 3: 78}
Dictionary Comprehension with Condition
This example stores only students who passed.
marks = {1: 35, 2: 80, 3: 60}
passed = {k: v for k, v in marks.items() if v >= 40}
print(passed)
3.Set Comprehension
What is Set Comprehension?
A set comprehension creates a set (unique values only).
Syntax
new_set = {expression for item in iterable if condition}
Simple Set Comprehension
This example removes duplicate values.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = {n for n in numbers}
print(unique_numbers)