Python List Comprehension

Build lists in one line.

✍️ 3 exercises + code challenge in this lesson

A list comprehension creates a new list from an existing iterable in a single, readable line:

new_list = [expression for item in iterable if condition]

  • [x * 2 for x in nums]: transform every item.
  • [x for x in nums if x > 0]: keep only some items.
  • [x if x > 0 else 0 for x in nums]: choose a value per item.

The same syntax works for sets {...} and dictionaries {k: v ...}.

Key Takeaways: Python List Comprehension

Mastering Python List Comprehension helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python List Comprehension Code Example

Python
nums = [3, -1, 8, 0, -5, 12]

doubled = [n * 2 for n in nums]
positives = [n for n in nums if n > 0]
clamped = [n if n > 0 else 0 for n in nums]
squares = {n: n ** 2 for n in range(1, 6)}

print(doubled)
print(positives)
print(clamped)
print(squares)
Free sign-in required · Google login available

Python List Comprehension Practice Exercises

Check what you learned in “Python List Comprehension”.

/ 3 solved
Fill in the blank

Create a list of squares.

squares = [x * x  x in range(5)]
✓ Correct! Not quite. Try again.
Multiple choice

What does [n for n in nums if n > 0] produce?

✓ Correct! Not quite. Try again.
Code challenge

Use a list comprehension to print the even numbers from 1 to 10.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services