![]() |
---|
Photo by Brecht Corbeel on Unsplash |
When you first learn Python, you’re introduced to for
loops. They work fine, but once you want faster, cleaner, and more professional-looking code, Python offers a beautiful shortcut called List Comprehensions.
List comprehensions condense loops into a single line without sacrificing readability, and in many cases, they make your code more intuitive.
In simple terms, list comprehension is a concise way to create lists based on existing lists (or any iterable). Instead of writing multiple lines to build a list, you do it all in one elegant line.
new_list = [expression for item in iterable if condition]
squares = []
for i in range(10):
squares.append(i ** 2)
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [i ** 2 for i in range(10)]
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
*Did you see how shorter and cleaner it is?*
Suppose you want only even squares
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
even_squares
[0, 4, 16, 36, 64]
*This is what called as a one-liner!*
List comprehension can be nearly twice as fast as traditional for
loops because they’re optimized at the C level internally by Python!
List comprehensions are a must-know technique for anyone who wants to write efficient, clean, and Pythonic code. Master them, and you’ll instantly level up the quality (and speed) of your Python scripts. I hope you learned something new today! Suggestions and comments are welcomed in the comment section. Until then, see you next time. Happy Coding!