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)