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)