It was one of those late-night coding marathons.
My script was running fine, but every time I looked at the for
loop, something felt... heavy.
squares = []
for _ in range(10):
squares.append(_ * _)
Wait... I wasn’t even using the variable for anything besides its own value.
And even when I did need it, the loop itself just felt too verbose.
👀 The Realization
Then I saw this in a Python blog post:
squares = [ _ * _ for _ in range(10) ]
That’s it? That’s legal?
One line. No .append()
. No unnecessary scaffolding.
✅ Cleaner
✅ Way more readable
✅ One-liner magic
✅ Still 100% Pythonic
🧐 Why it works:
List comprehensions are designed to build lists efficiently.
They're expressive, compact, and a dream for transformations or filtering.
Want to filter as well?
evens = [ _ for _ in range(20) if _ % 2 == 0 ]
Compare that to the old-fashioned way, and it’s no contest.
🚫 Never Again...
After discovering it, I rarely go back to full for
loops for simple list building.
Now, list comprehensions rule my scripts.
✨ Moral of the Story:
If you're writing a loop just to make a list...
Ask yourself—What would a list comprehension do? 😎
📖 For more tips and tricks in Python, check out
Packed with hidden gems, Python's underrated features and modules are real game-changers when it comes to writing clean and efficient code.
Top comments (0)