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:
- Move the thing you append to the front. n * n goes first.
- Copy the for line right after it. for n in numbers
- 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:


Python List Comprehension Examples
Good Python list comprehension examples teach faster than rules. If you’re new to Python itself, our Python basics guide is a good place to warm up first.
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 goes | Example |
| Drop some items | At the end | [n for n in nums if n > 2] |
| Change items by rule | At 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 …}.
- Set comprehension: Uses {item …} and drops repeats. If you’re not sure how lists, tuples, and sets differ, read our lists, tuples, and sets comparison.
- Pandas: You can loop over a column the same way. This is handy in data science work.
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 comprehension | For loop | |
| Readability | Great for simple jobs | Better for long steps |
| Speed | Often a little faster | Fine for most work |
| Flexibility | Builds one list | Can do anything |
| Side effects (printing, saving) | Not a good fit | A 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.
For more habits like these, our Python tips and tricks post has a few more.
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]Interview favorites: the generator expression difference, flattening a list of lists, and when to pick a loop. These come up often in software developer interviews.
Python List Comprehension Cheat Sheet
Here is a handy cheat sheet for list comprehension.
| Task | Pattern |
| 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.
And if you think you’re ready to go further, our AI for beginners course might be for you; it builds on these Python skills and takes you further. You can also take a look at our other LetsLearn courses to find the right next step.
A Python list comprehension provides a means of creating a new list from an existing list all in one line. To do this, you use an expression, together with a for loop, and if necessary an if statement, everything being included in a single line. It does not alter the original list.
The word “comprehension” derives from “set comprehension” in mathematics, where it is employed to denote sets; Python introduced this concept in version 2.0, and since the language works with lists, it was referred to as list comprehension.
A list is a data type that can contain several items, and a list comprehension is a method of creating a list; in this case, one might think of a list as being like a box and the other as a quick way of filling that box.
It depends. For simple building and filtering, it’s shorter and clearer. For long steps or side effects, it can be hard to read, so a for loop is the better choice.
A Python list comprehension is mostly a little faster for simple list building. But it depends on the code and the Python version. We usually choose it for clarity and clean code; speed is not the main concern when choosing it.
No. A Python list comprehension makes the whole list in memory right away. If you want lazy values, use a generator expression with round brackets.
Put the if else at the front, before the for. Like this: [“yes” if n > 2 else “no” for n in nums]. It changes items instead of dropping them.
Yes. You can join the terms with and or or after the for. You can also add more than one if statement. Each of those works as an extra filter.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
The main difference at a glance is the type of brackets: list comprehension uses square brackets while generator expressions use round brackets. The other, more important difference is that a list comprehension builds the entire list and returns it; a generator expression returns the terms from the list one by one.
You should not use list comprehension when it makes the code less readable, so it’s not a good idea to use list comprehension when it’s too complex and long.






