Python Comprehensions Tutorial | List, Dictionary & Set Comprehensions
As Python developers gain experience, they look for ways to write cleaner, shorter, and more efficient code. Comprehensions are one of Python’s most powerful features that allow you to create lists, dictionaries, and sets using a single, readable line of code.
Instead of writing multiple lines using loops and conditional statements, comprehensions make your programs more concise while maintaining readability. They are widely used in Artificial Intelligence, Data Science, Web Development, Automation, Data Analytics, and Backend Development because they improve productivity and often provide better performance than traditional loops.
In this lesson, you’ll learn how to create list, dictionary, and set comprehensions, use conditional expressions, build nested comprehensions, compare them with traditional loops, and apply them in real-world software development.
By the end of this lesson, you’ll be able to write elegant, Pythonic code that is easier to understand and maintain.
Learning Objectives
After completing this lesson, you will be able to:
- Understand Python comprehensions.
- Create list comprehensions.
- Create dictionary comprehensions.
- Create set comprehensions.
- Apply conditions in comprehensions.
- Build nested comprehensions.
- Improve code readability and performance.
- Use comprehensions in real-world applications.
Topics Covered
- Introduction to Comprehensions
- List Comprehensions
- Conditional List Comprehensions
- Nested List Comprehensions
- Dictionary Comprehensions
- Set Comprehensions
- Performance Comparison
- Real-World Examples
- Best Practices
Detailed Lesson Content
Introduction to Comprehensions
Imagine you’re developing an AI-Based Student Performance Dashboard.
You need to:
- Filter students who passed.
- Convert marks into grades.
- Remove duplicate skills.
- Create dictionaries of student records.
Using traditional loops requires many lines of code.
Python provides Comprehensions, allowing these tasks to be completed in a clean, readable, and efficient way.
What is a Comprehension?
A comprehension is a concise way of creating collections using a single expression.
Instead of:
numbers = []
for i in range(5):
numbers.append(i)
Use:
numbers = [i for i in range(5)]
Both produce the same output.
List Comprehension
Syntax
[expression for item in iterable]
Example
numbers = [i for i in range(1,11)]
print(numbers)
Output
[1,2,3,4,5,6,7,8,9,10]
Squaring Numbers
Traditional Loop
squares = []
for i in range(1,6):
squares.append(i*i)
print(squares)
List Comprehension
squares = [i*i for i in range(1,6)]
print(squares)
Output
[1,4,9,16,25]
Conditional List Comprehension
Example
even_numbers = [i for i in range(1,21) if i % 2 == 0]
print(even_numbers)
Output
[2,4,6,8,10,12,14,16,18,20]
Using if…else in Comprehension
result = ["Pass" if marks >= 40 else "Fail"
for marks in [85,34,75,29]]
Output
['Pass','Fail','Pass','Fail']
Nested List Comprehension
Example
matrix = [[row,column]
for row in range(3)
for column in range(3)]
print(matrix)
Output
[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
Nested comprehensions are useful for matrix operations and AI data preprocessing.
Dictionary Comprehension
Syntax
{key:value for item in iterable}
Example
square = {i:i*i
for i in range(1,6)}
print(square)
Output
{1:1,2:4,3:9,4:16,5:25}
Conditional Dictionary Comprehension
students = {
"Rahul":85,
"Priya":95,
"Amit":35
}
passed = {
name:marks
for name,marks in students.items()
if marks >= 40
}
print(passed)
Output
{'Rahul':85,'Priya':95}
Set Comprehension
Example
numbers = {
i*i
for i in range(1,6)
}
print(numbers)
Output
{1,4,9,16,25}
Sets automatically remove duplicate values.
Comparing Traditional Loop vs Comprehension
Traditional Loop
names = []
for student in students:
names.append(student)
Comprehension
names = [student for student in students]
Advantages:
- Less code
- Better readability
- Faster execution
- More Pythonic
Real-World Example 1: Student Grades
marks = [95,82,70,45,30]
grades = [
"A" if mark >= 90
else "B" if mark >= 75
else "C"
for mark in marks
]
print(grades)
Real-World Example 2: Product Discount
prices = [500,1000,2000]
discount = [
price * 0.9
for price in prices
]
print(discount)
Real-World Example 3: Email Extraction
students = [
{"name":"Rahul",
"email":"rahul@gmail.com"},
{"name":"Priya",
"email":"priya@gmail.com"}
]
emails = [
student["email"]
for student in students
]
print(emails)
Real-World Example 4: AI Data Cleaning
data = [10,15,20,20,30,40,40]
unique = {
value
for value in data
}
print(unique)
Output
{10,15,20,30,40}
Performance Comparison
For most data transformation tasks:
- Comprehensions are generally faster than traditional loops.
- They require fewer lines of code.
- They improve readability.
However, avoid using extremely complex comprehensions that reduce code clarity.
Common Mistakes
Creating Complex Nested Comprehensions
Avoid writing deeply nested expressions that are difficult to understand.
Forgetting the Condition Position
Incorrect
[i if i%2==0
for i in range(10)]
Correct
[i
for i in range(10)
if i%2==0]
Using Comprehensions for Side Effects
Do not use comprehensions only to print values.
Incorrect
[print(i)
for i in range(5)]
Use a normal loop instead.
Best Practices
- Use comprehensions for simple transformations.
- Avoid overly complex nested expressions.
- Prefer readability over shortening code.
- Use dictionary comprehensions for structured data.
- Use set comprehensions to remove duplicates.
- Use meaningful variable names.
Key Takeaways
- Comprehensions create collections efficiently.
- List comprehensions simplify list creation.
- Dictionary comprehensions generate key-value pairs.
- Set comprehensions remove duplicates automatically.
- Conditional comprehensions filter data.
- Nested comprehensions process multidimensional data.
- Comprehensions produce cleaner and faster Python code.



