Mastering Python List Comprehensions: Conditions and Nested Loops
Mastering Python List Comprehensions: Conditions and Nested Loops ๐ ️
List comprehension is one of the best tools to write clean and efficient Python code.
Today, let's dive deeper by adding conditions and even nesting loops inside list comprehensions.
✅ Basic List Comprehension
Create simple lists in a clean, one-liner style:
# Basic list comprehension
numbers = [x for x in range(5)]
print(numbers) # [0, 1, 2, 3, 4]
✅ Adding a Condition
Filter elements during list creation by adding an if condition.
# Adding a condition
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # [0, 2, 4, 6, 8]
✅ Nested Loops
Flatten 2D arrays or handle multiple iterations with a nested loop inside the comprehension.
# Nested loops (flattening a 2D list)
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6]
Mastering list comprehensions not only shortens your code but also improves readability. Just remember: if it starts to look too complex, consider splitting it for clarity!
Short code, strong code. Refining your skills in the basics builds unstoppable momentum. Stay sharp, stay growing — you're building your future! ๐
Icons by Flaticon
Comments
Post a Comment