Welcome to Day 28 of the 100 Days of Python series!
Today, we’re diving into one of Python’s most elegant and powerful features: List Comprehensions.
If you’ve ever written a loop just to create a list, Python has a much shorter — and cleaner — way of doing it. List comprehensions let you generate lists with less code and more readability.
🎯 What You'll Learn
- What list comprehensions are
- Basic syntax and examples
- How to add conditions (if/else)
- Nested list comprehensions
- Real-world use cases
🧱 What is a List Comprehension?
A list comprehension is a concise way to create lists using a single line of code.
🔹 Basic Syntax:
[expression for item in iterable]
This is equivalent to:
result = []
for item in iterable:
result.append(expression)
🔍 Example 1: Squaring Numbers
✅ With loop:
squares = []
for i in range(5):
squares.append(i ** 2)
✅ With list comprehension:
squares = [i ** 2 for i in range(5)]
🔍 Example 2: Convert Strings to Uppercase
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names) # ['ALICE', 'BOB', 'CHARLIE']
❓ Why Use List Comprehensions?
- ✅ Shorter and cleaner syntax
- ✅ Faster performance
- ✅ More readable for simple transformations
🔀 Adding Conditions
🔸 Syntax:
[expression for item in iterable if condition]
Example: Even Numbers Only
evens = [i for i in range(10) if i % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
🔄 With if-else
in Expression
labels = ["even" if i % 2 == 0 else "odd" for i in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']
🔁 Nested List Comprehensions
You can even nest comprehensions, especially useful for 2D lists or matrices.
Example: Flatten a 2D List
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened) # [1, 2, 3, 4, 5, 6]
🧪 Real-World Examples
✅ 1. Extract Digits from String
text = "Age: 24, Score: 89"
digits = [char for char in text if char.isdigit()]
print(digits) # ['2', '4', '8', '9']
✅ 2. Filter Valid Emails
emails = ["a@gmail.com", "b@site", "c@yahoo.com"]
valid = [email for email in emails if "@" in email and "." in email]
print(valid) # ['a@gmail.com', 'c@yahoo.com']
✅ 3. Remove Duplicates from List
data = [1, 2, 2, 3, 4, 4]
unique = list({x for x in data})
print(unique) # [1, 2, 3, 4]
🧠 Tips & Best Practices
- 👍 Use list comprehensions for simple transformations
- 🚫 Avoid making them too complex or nested too deeply — use loops for readability
- 🧹 Clean and readable comprehensions can improve performance and clarity
📚 Bonus: Dictionary & Set Comprehensions
Python also supports:
🧾 Dictionary Comprehension
squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
🔁 Set Comprehension
unique = {char for char in "hello"}
# {'h', 'e', 'l', 'o'}
🧭 Recap
Today you learned:
- What list comprehensions are
- How to use them with conditions
- When to use
if
,if-else
, and nested comprehensions - Real-world practical examples
- Bonus: dictionary and set comprehensions
Top comments (0)