Python List Comprehension

Python List Comprehension: Syntax, Examples, If-Else, and Best Practices (2026 Guide)

You can use Python list comprehension to create a list in a single short line. Without it, you would need four or five lines using a loop. With it, you only need one. 

Doesn’t sound easy, does it? Many people just getting started struggle. All the brackets, the for, and the if are on the same line, and the order seems odd.

The guide solves this problem. We’ll proceed step by step, using small examples together with the output for each one. You’ll be able to see how Python list comprehension works, the situations in which it is useful, and the ones in which a simple loop is the better choice. Since we teach Python to beginners at LetsLearn every week, we know what confuses people and will cover those points as well.

Quick answer: A Python list comprehension creates a new list from an existing one by using the following pattern : [expression for item in iterable if condition]. The if part is optional.

What Is List Comprehension in Python?

Python list comprehension is a method for creating a list; you take the items from an existing list, alter them if desired, and then gather the results. The entire process takes place within a pair of square brackets. 

Imagine the photo day at school when the teacher says, “Anyone taller than 140 cm, come forward.” That is an example of a filter. In a similar way, a Python list comprehension carries out the same function with numbers or words. 

  • Why is it called “comprehension”? The name comes from mathematics, where sets are written in a concise form such as “all even numbers up to 10”. Python took this idea from mathematics and included it in Python 2.0 via a proposal known as PEP 202. 
  • It makes a new list. A Python list comprehension will never alter your original list. 

A plain list is the box. A comprehension is a fast way to fill it. So [1, 2, 3] is typed by hand, and [n * 2 for n in [1, 2, 3]] is built from a rule.

Why do people prefer it? It contains less code, and once you’ve got the pattern, it reads like a sentence, and you’ll encounter list comprehension in Python in almost every codebase. 

Python List Comprehension Syntax

Here’s the basic pattern of a Python list comprehension:

new_list = [expression for item in iterable if condition]

It has three parts:

  • Expression: What goes into the new list. It can be the item itself (n) or something done to it (n * 2).
  • Iterable: The thing you loop over, like a list or range(10).
  • Optional condition: An if that decides which items get in. Leave it out and every item goes in.

How List Comprehension Works

Let’s start with a loop you probably know. We want the square of each number.

numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
    squares.append(n * n)
print(squares)  # [1, 4, 9, 16, 25]

Now the same job as a Python list comprehension:
squares = [n * n for n in numbers]
print(squares)  # [1, 4, 9, 16, 25]

Same answer. Less typing.

Turn any for loop into a Python list comprehension in 3 steps:

  1. Move the thing you append to the front. n * n goes first.
  2. Copy the for line right after it. for n in numbers
  3. Add the if at the end, if your loop had one. Then wrap it all in [ ].

Here’s a picture of how Python reads it:

how list comprehension works

Python List Comprehension Examples

Numbers and ranges

evens = [n for n in range(1, 11) if n % 2 == 0]

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

Strings

names = ["asha", "bikash", "sita"]

print([name.title() for name in names])  # ['Asha', 'Bikash', 'Sita']

Real-world jobs: find cheap items, clean messy text, and drop missing data.

prices = [120, 450, 80, 300]

print([p for p in prices if p < 200])  # [120, 80]

raw = ["  Ram ", "Sita  ", " "]

print([s.strip() for s in raw if s.strip()])  # ['Ram', 'Sita']

Want to add items to a list in Python using list comprehension? You don’t append inside it. Build a fresh list, or join two with +.

Python List Comprehension With If

In a Python list comprehension, the if goes at the end. It works like a filter.

  • Filtering values: [n for n in nums if n > 10] keeps only numbers above 10.
  • Multiple conditions: Join tests with and or or.
  • Removing None values: Use is not None, not != None.
  • Conditional inclusion: Items that fail the test never enter the list.
print([n for n in range(1, 21) if n % 2 == 0 and n % 3 == 0])  # [6, 12, 18]

print([n for n in range(1, 11) if n < 3 or n > 8])            # [1, 2, 9, 10]

data = [4, None, 7, None, 9]

print([x for x in data if x is not None])                      # [4, 7, 9]

Python List Comprehension If Else

Python list comprehension if else is where most people trip. When you use if else, it moves to the front.

  • Basic if else: You change each item. You don’t drop any.
  • Elif logic: There’s no real elif. Chain more if else pieces instead.
  • If without else: That’s the filter from the last section, and it goes at the end.
print(["even" if n % 2 == 0 else "odd" for n in range(1, 6)])

# ['odd', 'even', 'odd', 'even', 'odd']

A simple rule to remember:

You want to…Where if goesExample
Drop some itemsAt the end[n for n in nums if n > 2]
Change items by ruleAt the front, with else[n if n > 2 else 0 for n in nums]

Nested List Comprehension in Python

A nested Python list comprehension has two for parts. The first for is the outer loop. The second is the inner loop.

  • Nested loops: Read left to right, just like nested for loops.
  • Matrix work: Put one comprehension inside another.
  • Flattening lists: Turn a list of lists into one list.
pairs = [(x, y) for x in [1, 2] for y in ["a", "b"]]

print(pairs)  # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

matrix = [[1, 2, 3], [4, 5, 6]]

print([n for row in matrix for n in row])        # [1, 2, 3, 4, 5, 6]

If you need more than two loops, you will need to use a regular loop instead.

Working With Dictionaries, Sets, Zip, and Pandas

List comprehension has cousins. The idea is the same, but the brackets change.

  • Zip: Iterates through two lists at once.
  • Dictionary comprehension: Uses {key: value …}.
names = ["Asha", "Bikash"]

marks = [80, 90]

print([f"{n}: {m}" for n, m in zip(names, marks)])  # ['Asha: 80', 'Bikash: 90']

print({n: len(n) for n in names})                    # {'Asha': 4, 'Bikash': 6}

For big tables, pandas has faster built-in tools. Use a comprehension for small jobs.

List Comprehension vs For Loop

Neither always wins. Pick the one a teammate can read fastest.

List comprehensionFor loop
ReadabilityGreat for simple jobsBetter for long steps
SpeedOften a little fasterFine for most work
FlexibilityBuilds one listCan do anything
Side effects (printing, saving)Not a good fitA good fit

Is it faster? Usually, a little, for simple list building. But tests disagree. Some show a big gap. Others show almost none, and some show the loop winning when a function call sits inside. So we don’t pick list comprehension for speed; we do it to make the code cleaner and more Pythonic.

A for loop wins when you have many steps, need to print or save each time, or the one-liner is too long to read.

List Comprehension vs Map and Lambda

map() and filter() do the same jobs. Most Python writers prefer a Python list comprehension because it reads more clearly.

nums = [1, 2, 3]

print(list(map(lambda n: n * 2, nums)))  # [2, 4, 6]

print([n * 2 for n in nums])             # [2, 4, 6]
  • map(): Changes each item. A comprehension does it with no lambda.
  • filter(): Keeps some items. A comprehension uses an if instead.

List Comprehension vs Generator Expression

A generator expression looks almost the same, but it uses round brackets.

squares_list = [n * n for n in range(5)]  # builds the whole list now

squares_gen = (n * n for n in range(5))   # makes values only when asked
  • Python list comprehension: Not lazy. It builds the full list in memory right away.
  • Generator expression: Lazy. It hands out one value at a time.
  • Use a generator when the data is huge.

Common Mistakes

These Python list comprehension mistakes show up in our classes again and again.

  • Wrong if statement. [n for n in nums if n > 2 else 0] gives a SyntaxError. Use [n if n > 2 else 0 for n in nums].
  • A list full of None. Using .append() or print() inside gives None for every item.
  • Side effects. [print(x) for x in items] builds a useless list. Use a loop.
  • Giant one-liners. Can’t read it in ten seconds? Break it up.

Practice Problems and Interview Questions

Practice Python list comprehension with these before you look at the answers.

Beginner: Cube the numbers 1 to 5. Answer: [n ** 3 for n in range(1, 6)]

Prime numbers up to 30:

primes = [n for n in range(2, 30) if all(n % d != 0 for d in range(2, n))]

print(primes)  # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Python List Comprehension Cheat Sheet

Here is a handy cheat sheet for list comprehension.

TaskPattern
Change every item[f(x) for x in items]
Keep some items[x for x in items if test]
Change by rule[a if test else b for x in items]
Two loops[(x, y) for x in A for y in B]
Flatten[x for row in rows for x in row]

JavaScript equivalent: JavaScript chains filter() and map() instead:

nums.filter(n => n % 2 === 0).map(n => n * n)

Key Takeaways

  • A Python list comprehension builds a new list in one line using [expression for item in iterable if condition].
  • A filter if goes at the end. An if else goes at the front.
  • Every Python list comprehension is eager, not lazy. Use a generator for lazy values.
  • Clarity is the real reason to use it. Speed is a small bonus.

Next Steps for Learning Python

Reading is a good way of learning, but when it comes to coding, typing it out and practicing is the best method. Try to play around with the list comprehensions on this blog; try to break them, see how they work. You will learn a lot more that way.

Leave a Comment

Student Registration