DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python List Comprehensions Explained Simply (Concise Syntax)

List comprehensions provide a short and readable way to create new lists based on existing ones. They combine loops and conditions in one line.

What is a list comprehension?

A basic list comprehension looks like this:

numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
print(squares)  # [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

The structure is:
[new_value for item in sequence]

It works like a for loop but written inside square brackets.

Adding conditions

Filter items with an if clause:

even_squares = [x * x for x in numbers if x % 2 == 0]
print(even_squares)  # [4, 16]
Enter fullscreen mode Exit fullscreen mode

Only items where the condition is True are included.

More examples

Double values greater than 3:

doubled = [x * 2 for x in numbers if x > 3]
print(doubled)  # [8, 10]
Enter fullscreen mode Exit fullscreen mode

Convert strings to uppercase:

words = ["hello", "world", "python"]
upper = [word.upper() for word in words]
print(upper)  # ['HELLO', 'WORLD', 'PYTHON']
Enter fullscreen mode Exit fullscreen mode

Replace values conditionally:

adjusted = [x + 1 if x < 3 else x - 1 for x in numbers]
print(adjusted)  # [2, 3, 4, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Equivalent with regular loops

The same result without comprehension:

squares = []
for x in numbers:
    squares.append(x * x)
Enter fullscreen mode Exit fullscreen mode

Comprehensions are shorter and often clearer for simple cases.

Important notes

  • Use comprehensions for simple transformations and filters.
  • Avoid complex logic (multiple nested loops or long conditions) to keep code readable.
  • They create a new list; the original stays unchanged.

Quick summary

  • Basic form: [expression for item in sequence]
  • Add filter: [expression for item in sequence if condition]
  • Add if-else: [expr1 if condition else expr2 for item in sequence]
  • Great for creating transformed or filtered lists quickly.

Practice rewriting simple for loops as comprehensions. They make Python code more concise and elegant.

Top comments (0)