🎯 List Comprehensions
List comprehensions are a concise and elegant way to create lists in Python. They combine the power of loops and conditional statements into a single line, making your code more readable and efficient.
# Basic list comprehension
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
print(f"Numbers: {numbers}")
print(f"Squares: {squares}")
🎨 Basic List Comprehension
A list comprehension consists of an expression followed by a for
clause. It's like a compact for
loop that creates a new list.
Simple Examples
# Different ways to use list comprehensions
# 1. Double numbers
numbers = [1, 2, 3, 4, 5]
doubled = [n * 2 for n in numbers]
print(f"Doubled: {doubled}")
# 2. Convert to uppercase
words = ["python", "is", "fun"]
upper_words = [word.upper() for word in words]
print(f"Uppercase: {upper_words}")
# 3. Get lengths
texts = ["hello", "world", "python"]
lengths = [len(text) for text in texts]
print(f"Lengths: {lengths}")
🔍 Conditional List Comprehensions
You can add conditions to filter items or modify the expression based on certain criteria.
Filtering Examples
# Filtering with list comprehensions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Get even numbers
evens = [n for n in numbers if n % 2 == 0]
print(f"Even numbers: {evens}")
# Get numbers greater than 5
big_numbers = [n for n in numbers if n > 5]
print(f"Numbers > 5: {big_numbers}")
# Get squares of even numbers
even_squares = [n * n for n in numbers if n % 2 == 0]
print(f"Squares of evens: {even_squares}")
🎯 Nested List Comprehensions
You can create more complex transformations using nested list comprehensions.
# Nested list comprehensions
# 1. Create a multiplication table
table = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print("Multiplication table:")
for row in table:
print(row)
# 2. Flatten a nested list
nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in nested for num in row]
print(f"Flattened: {flat}")
📝 Quick Practice
Let's practice using list comprehensions with a simple exercise!
Hands-on Exercise
Create a list of squared even numbers from 1 to 10.
# List Comprehension Practice
numbers = range(1, 11) # 1 to 10
# TODO: Create a list of squared even numbers
# 1. Filter even numbers
# 2. Square each number
# 3. Store in a list
# Print the result
print(f"Squared evens: {squared_evens}")
Solution and Explanation 💡
Click to see the solution
# List Comprehension Practice Solution
numbers = range(1, 11) # 1 to 10
# Create list of squared even numbers
squared_evens = [n * n for n in numbers if n % 2 == 0]
print(f"Squared evens: {squared_evens}")
Key Learning Points:
- 📌 Used
range(1, 11)
to generate numbers 1-10 - 📌 Used
if n % 2 == 0
to filter even numbers - 📌 Used
n * n
to square each number - 📌 Combined everything in a single list comprehension
🎯 Key Takeaways
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.