๐ Phase 1: Programming Fundamentals
๐ Topic 8: Python List Comprehensions
Welcome back! ๐
In the previous lesson, you learned about Python's built-in data structuresโLists, Tuples, Sets, and Dictionaries.
Now it's time to learn one of Python's most elegant and frequently used features: List Comprehensions.
List comprehensions provide a concise and readable way to create, filter, and transform lists. They are widely used in Data Science, Machine Learning, data preprocessing, and coding interviews.
๐น 1. What is a List Comprehension?
A list comprehension is a compact way to create a new list by applying an expression to each item in an iterable (such as a list, tuple, or range).
Instead of writing multiple lines with a loop, you can accomplish the same task in a single line.
General Syntax
new_list = [expression for item in iterable]๐น 2. Creating a List Using a Loop
numbers = []
for i in range(5):
numbers.append(i)
print(numbers)
Output
[0, 1, 2, 3, 4]
๐น 3. Creating the Same List Using List Comprehension
numbers = [i for i in range(5)]
print(numbers)
Output
[0, 1, 2, 3, 4]
Notice how the code is shorter and easier to read.
๐น 4. Performing Calculations
Create a list of squares.
squares = [x ** 2 for x in range(1, 6)]
print(squares)
Output
[1, 4, 9, 16, 25]
๐น 5. Using Conditions
You can filter elements while creating a list.
Example: Even Numbers
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)
Output
[2, 4, 6, 8, 10]
๐น 6. Converting Strings
Convert all names to uppercase.
names = ["rahul", "deepak", "anita"]
upper_names = [name.upper() for name in names]
print(upper_names)
Output
['RAHUL', 'DEEPAK', 'ANITA']
๐น 7. Using Conditional Expressions
Replace negative numbers with zero.
numbers = [5, -2, 8, -1, 3]
updated = [0 if x < 0 else x for x in numbers]
print(updated)
Output
[5, 0, 8, 0, 3]
๐น 8. Nested List Comprehension
Create a multiplication table.
table = [[i * j for j in range(1, 6)] for i in range(1, 4)]
print(table)
Output
[[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15]]
๐น 9. Real-World Data Science Example
Suppose you have a list of sales amounts.
sales = [1200, 850, 1500, 600, 2000]
high_sales = [sale for sale in sales if sale > 1000]
print(high_sales)
Output
[1200, 1500, 2000]
This technique is commonly used while cleaning and filtering datasets before analysis.
๐น 10. Benefits of List Comprehensions
โ Shorter code
โ Easier to read
โ Faster than traditional loops in many cases
โ Widely used in Data Science and Machine Learning
๐น 11. Common Mistakes
โ Forgetting the Expression
numbers = [for i in range(5)] # SyntaxError
Correct:
numbers = [i for i in range(5)]
โ Incorrect Order of "if"
numbers = [if x % 2 == 0 x for x in range(10)] # SyntaxError
Correct:
numbers = [x for x in range(10) if x % 2 == 0]