Sitemap
Dicki Haris Sujadi

Dicki Haris Sujadi

Python — List Comprehensions

1 min readNov 7, 2025

--

What?

it is a Python features

Why?

  • easy to understand
  • quick to write

Pros and Cons

  • very powerfull tool ✅
  • example of high-quality code ✅
  • require more memory and run more slowly ❌

Get Dicki Haris Sujadi’s stories in your inbox

Join Medium for free to get updates from this writer.

The Idea

instead of writing this:

numbers = [1,2,3,4,5]

new_numbers = []

for n in numbers:
new_numbers.append(n ** 2)

print(new_numbers) # [2, 4, 6, 8, 10]

do this:

numbers = [1,2,3,4,5]

new_numbers = [n * 2 for n in numbers]

print(new_numbers) # [2, 4, 6, 8, 10]

another example, instead of do this:

for i in range(2):
for j in range(5):
print(i + j, end = " ")

# 0 1 2 3 4 1 2 3 4 5

do this:

new_numbers = [i + j for i in range(2) for j in range(5)]
print(new_numbers) # [0, 1, 2, 3, 4, 1, 2, 3, 4, 5] <= a list
new_numbers = [[i+j for i in range(2)] for j in range(5)]
print(new_numbers) # [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
list(range(1,11)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[num ** 3 for num in list(range(1,11)) if num % 2 != 0] # ✅ [1, 27, 125, 343, 729]

[num ** 3 if num % 2 != 0 for num in list(range(1,11))] # ❌ ERROR ! it will ask for else condition, add it! or ...

# place the condition on the right

--

--