Python List Comprehensions with Examples
Replace a four-line loop with one readable line that transforms and filters a list.
- The [expression for item in iterable] form
- Filtering with if
- Dict and set comprehensions
- 1
for n in range(1, 11)Take each number - 2
if n % 2 == 0Keep the even ones - 3
n * nSquare them - 4
[4, 16, 36, 64, 100]Collect the results
Loop, filter and result in one expression
The problem
A very common task is building a new list from an old one: square every number, keep only the passing scores, clean every name. With a normal loop that takes four lines and an empty list to start with, and the intent gets lost in the details.
Think of it like this
A list comprehension is like a sorting conveyor in a factory. Items move along the belt one by one, a gate lets through only the ones that pass a check, and a machine changes each item that passes before it drops into a new box.
for number in numbers🏭 Items move along the beltif number % 2 == 0🚦 The gate lets only even numbers throughnumber ** 2⚙️ The machine squares each one[...]📦 Everything lands in a new box (list)A list comprehension builds a new list in one expression: [result for item in items if condition].
Key points
numbers = range(1, 11)gives the numbers 1 to 10.for number in numbersgoes through them;if number % 2 == 0keeps only the even ones.number ** 2is applied to each number that passed the filter.- The result is a brand-new list;
numbersis not changed.
When should you use it?
- Transforming every item: prices with tax, names in upper case, lengths of words.
- Filtering: passing scores, non-empty lines, files with a given extension.
- Doing both in one readable line when the rule is simple.
When not to use it
- The logic needs several steps, nested conditions or
try/except: a normal loop is clearer. - You only need the total or the count:
sum()or a generator avoids building a list.
See how it works
Press Step to send each number through the condition and the expression. Change the condition or the expression to build another list.
Example code
numbers = range(1, 11)
even_squares = [number ** 2 for number in numbers if number % 2 == 0]
print(even_squares)
Result of running the code
[4, 16, 36, 64, 100]
Code explanation
The comprehension reads from left to right like a sentence: square the number, for each number in numbers, if the number is even. Python checks the condition first and only squares the values that pass, so the result holds the squares of 2, 4, 6, 8 and 10. numbers itself is left as it was.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Common mistakes
Putting the condition in the wrong place
A filter goes at the end. A value that depends on a condition uses if ... else before for.
[number ** 2 if number % 2 == 0 for number in numbers]
[number ** 2 for number in numbers if number % 2 == 0]
Squeezing too much into one line
If you need comments to explain the comprehension, a loop is easier to read.
[x * y for x in a if x for y in b if y % x and y > 2]
result = []
for x in a:
for y in b:
if x and y % x and y > 2:
result.append(x * y)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Count Positive Numbers Count the values greater than zero in a list. Easy
- Above-Average Values Keep the values that are greater than the average. Easy
- Remove Duplicates Keep only the first occurrence of each value. Easy