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.