List Comprehensions

List comprehensions provide a concise way to create lists. They are more readable and often faster than using traditional for loops and .append().

1. Syntax Boilerplate

[expression for item in iterable if condition]

2. Basic Examples

# Traditional for loop
squares = []
for x in range(10):
    squares.append(x**2)

# List Comprehension
squares = [x**2 for x in range(10)]
print(squares)

3. Adding Conditionals

# Get only even numbers
evens = [n for n in range(50) if n % 2 == 0]

# Conditional Expression (if-else)
status = ["Pass" if score > 70 else "Fail" for score in [80, 50, 95]]

4. Nested Comprehensions

You can even flatten nested lists in one line!

matrix = [[1, 2], [3, 4]]
flat = [num for row in matrix for num in row] # [1, 2, 3, 4]
Efficiency: List comprehensions are generally faster because they are internally optimized for performance in the CPython interpreter.