📌 Quick Info

  • Topic: List comprehensions in Python
  • Target Audience: Beginners who know basic for loops
  • Goal: Teach a powerful Python feature without overusing it

1. Introduction

"When I first learned for loops, I used them for everything. Then a senior dev looked at my code and said, 'You know you can do that in one line, right?' That's when I discovered list comprehensions."

2. The Problem (The Traditional For Loop)

Let's say we have a list of numbers, and we want to square each one.

numbers = [1, 2, 3, 4, 5] squared_numbers = [] for num in numbers: squared_numbers.append(num * num) print(squared_numbers) # [1, 4, 9, 16, 25] 

The Problem: It takes 5 lines of code to do something very simple. It’s readable, but it’s a bit clunky.

3. The Solution (List Comprehension)

Here is the exact same logic in a single line:

numbers = [1, 2, 3, 4, 5] squared_numbers = [num * num for num in numbers] print(squared_numbers) 

Clean, fast, and Pythonic.

4. How It Works

The syntax is: [expression for item in iterable]

  • expression: What you want to do to each item (num*num).
  • item: The temporary variable name (num).
  • iterable: The List you are looping through (numbers).

5. Adding an IF Condition

You can also filter items. Let’s say we only want to square the even numbers:

numbers = [1, 2, 3, 4, 5] even_squared = [num * num for num in numbers if num % 2 == 0] print(even_squared) 

The if statement goes at the end.

6. When to AVOID List Comprehensions (The Danger Zone)

List comprehensions are amazing, but they can become unreadable if you try to do too much.

Example of bad code:

result = [[x for x in row if x > 0] for row in matrix if sum(row) > 10] 

If you have to stare at it for 30 seconds to figure out what it does, use a normal for loop. Readability always beats writing “clever” one-liners.

7. What I Learned

  • List comprehensions replace simple for loops that append to a list.
  • They make code shorter and often faster.
  • They support if statements for filtering.
  • Never sacrifice readability: If it gets too complex, go back to a for loop.

8. Conclusion

List comprehensions are a rite of passage in Python. Once you start using them, you'll never go back to the clunky 5-line for loop. Just remember: the goal isn't to write the shortest code, it's to write the most understandable code.