
You’ve probably written code like this many times, especially when exploring Python list comprehensions.
- Create an empty list.
- Start a
forloop. - Do some math or logic.
.append()the result to the list.
squares = []
for num in range(10):
squares.append(num * num)This works, but it’s 3 lines of code for a very simple task. Simplifying can help you reduce lines.
The “Pythonic” Way
List comprehensions let you do this in one line. It’s more readable (once you get used to it) and often faster. Using Python List Comprehensions makes your code concise and clean.
# [EXPRESSION for ITEM in ITERABLE]
squares = [num * num for num in range(10)]It reads like plain English: “Give me num * num FOR every num IN the range(10).”
Adding Conditions (if)
You can even add an if statement to filter items. By using PLC, we can easily keep even squares.
Old Way:
even_squares = []
for num in range(10):
if (num * num) % 2 == 0:
even_squares.append(num * num)New Way:
even_squares = [num * num for num in range(10) if (num * num) % 2 == 0]When NOT to use them
If your logic is very complex (multiple if/else statements, or nested loops), a list comprehension can become harder to read. In that case, stick to the standard loop. Readability always comes first! However, for simple tasks, utilising Python List Comprehensions is very handy.





