Python

Python List Comprehension — 15 Examples (If/Else, Nested, Dict, Set)

Master Python list comprehension with 15 worked examples — basic syntax, if filter, if-else transform, nested loops, dict comprehension, set comprehension, and common patterns.

List comprehension is a concise way to create lists in Python. Instead of writing a multi-line for loop, you can generate a list in a single line. This topic appears in CBSE Class 11 and 12 exams, and understanding it will help you write cleaner code and solve output-based questions faster.

Basic Syntax

new_list = [expression for item in iterable]

This is equivalent to:

new_list = []
for item in iterable:
    new_list.append(expression)

Example 1: Squares of Numbers

squares = [x ** 2 for x in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]

Without list comprehension:

squares = []
for x in range(1, 6):
    squares.append(x ** 2)

Example 2: Even Numbers from 1 to 20

evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

The if condition acts as a filter. Only elements that satisfy the condition are included.


Example 3: Odd Numbers from a List

numbers = [12, 7, 35, 42, 19, 8, 63]
odds = [n for n in numbers if n % 2 != 0]
print(odds)
[7, 35, 19, 63]

Example 4: Convert Strings to Uppercase

names = ["aman", "priya", "rahul"]
upper_names = [name.upper() for name in names]
print(upper_names)
['AMAN', 'PRIYA', 'RAHUL']

Example 5: Extract First Character of Each Word

words = ["Python", "Computer", "Science"]
initials = [w[0] for w in words]
print(initials)
['P', 'C', 'S']

Example 6: Lengths of Strings

fruits = ["apple", "banana", "cherry", "date"]
lengths = [len(f) for f in fruits]
print(lengths)
[5, 6, 6, 4]

Example 7: List Comprehension with if-else

When you need both if and else, the syntax changes. The conditional expression goes before the for keyword.

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
labels = ["even" if x % 2 == 0 else "odd" for x in numbers]
print(labels)
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']

Important syntax difference:

  • Filter only (if): [x for x in list if condition], the if comes after
  • Transform (if-else): [a if condition else b for x in list], the if-else comes before

This is a common source of confusion in exams.


Example 8: Replace Negatives with Zero

numbers = [5, -3, 8, -1, 0, 7, -6]
cleaned = [x if x >= 0 else 0 for x in numbers]
print(cleaned)
[5, 0, 8, 0, 0, 7, 0]

Example 9: Flatten a 2D List

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

This is a nested list comprehension. The outer loop (for row in matrix) runs first, then the inner loop (for num in row).

Equivalent regular code:

flat = []
for row in matrix:
    for num in row:
        flat.append(num)

Example 10: Multiplication Table

table_of_5 = [5 * i for i in range(1, 11)]
print(table_of_5)
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

Example 11: Filter Students Who Passed

marks = {"Aman": 85, "Priya": 32, "Rahul": 67, "Neha": 28, "Vikram": 91}
passed = [name for name, score in marks.items() if score >= 40]
print(passed)
['Aman', 'Rahul', 'Vikram']

You can use .items() to loop through a dictionary inside a list comprehension.


Example 12: Remove Vowels from a String

sentence = "Hello World"
vowels = "aeiouAEIOU"
no_vowels = [ch for ch in sentence if ch not in vowels]
print("".join(no_vowels))
Hll Wrld

Example 13: Generate Pairs (Nested Comprehension)

pairs = [(x, y) for x in range(1, 4) for y in range(1, 4) if x != y]
print(pairs)
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

This generates all pairs of numbers from 1 to 3 where the two numbers are not equal.


Example 14: Convert Celsius to Fahrenheit

celsius = [0, 10, 20, 30, 40]
fahrenheit = [(c * 9/5) + 32 for c in celsius]
print(fahrenheit)
[32.0, 50.0, 68.0, 86.0, 104.0]

Example 15: Divisible by Both 3 and 5

divisible = [x for x in range(1, 101) if x % 3 == 0 and x % 5 == 0]
print(divisible)
[15, 30, 45, 60, 75, 90]

Syntax Summary

Pattern Syntax Example
Basic [expr for x in iterable] [x*2 for x in range(5)]
With filter [expr for x in iterable if cond] [x for x in L if x > 0]
With if-else [a if cond else b for x in iterable] [x if x>0 else 0 for x in L]
Nested loops [expr for x in iter1 for y in iter2] [x*y for x in A for y in B]

When NOT to Use List Comprehension

List comprehension is great for simple transformations, but avoid it when:

  1. The logic is complex, If you need multiple conditions or complex calculations, a regular for loop is more readable.
  2. You do not need a list, If you only need to perform an action (like printing), use a regular loop.
  3. The expression is too long, If it does not fit comfortably in one line, break it into a loop.

Bad practice (too complex):

result = [x ** 2 if x % 2 == 0 else x ** 3 for x in range(20) if x % 3 != 0]

Better as a regular loop:

result = []
for x in range(20):
    if x % 3 != 0:
        if x % 2 == 0:
            result.append(x ** 2)
        else:
            result.append(x ** 3)

Common Exam Questions

Q1: What is the output?

L = [x * 2 for x in range(5)]
print(L)
[0, 2, 4, 6, 8]

Q2: Rewrite using list comprehension:

result = []
for i in range(1, 11):
    if i % 2 == 0:
        result.append(i ** 2)

Answer:

result = [i ** 2 for i in range(1, 11) if i % 2 == 0]
# [4, 16, 36, 64, 100]

Q3: What is the output?

words = ["Hi", "Hello", "Hey"]
result = [w.lower() for w in words if len(w) > 2]
print(result)
['hello', 'hey']

"Hi" has length 2, so it is filtered out.


Tips for the Exam

  1. If asked to "rewrite using list comprehension," identify the loop, the condition, and the expression.
  2. Remember the syntax difference between filter (if at the end) and transform (if-else at the beginning).
  3. For nested comprehensions, the outer loop comes first in the comprehension, same as in regular nested loops.
  4. List comprehension always creates a new list, it does not modify the original.

Mastering list comprehension will help you write Python code that is both concise and elegant, and it is a reliable way to pick up marks in the exam.


Frequently Asked Questions

Is list comprehension faster than a for loop in Python?

Usually yes, by 30-50% for simple transformations. The CPython interpreter has specialized bytecode for list comprehensions that avoids the overhead of repeated list.append() calls and method lookups inside a loop. The performance gap shrinks as the body grows; for complex logic with side effects, a regular for loop is more readable and not meaningfully slower.

When should I NOT use a list comprehension?

Avoid list comprehensions when:

  1. The logic doesn't fit on one line cleanly — if you'd need a comment to explain it, write a loop.
  2. You have side effects — list comprehensions are for producing lists. If your goal is "do something for each item" (write a file, call an API), use a for loop.
  3. The result is very large and you don't need it all at once — use a generator expression (x*2 for x in nums) instead. It produces values one at a time without building the full list in memory.

What is the difference between a list comprehension and a generator expression?

Syntax: square brackets [...] for list comprehension, parentheses (...) for generator expression. Behavior: list comprehension builds the full list immediately in memory; generator expression yields one value at a time as you iterate.

sq_list = [x*x for x in range(10**7)]   # Builds 10 million items immediately
sq_gen  = (x*x for x in range(10**7))   # Lazy, near-zero memory

Use a generator when feeding sum(), max(), any(), or any function that consumes one value at a time.

Can I have multiple if conditions in a list comprehension?

Yes. Multiple filters can be stacked:

result = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]
print(result)  # [0, 6, 12, 18]

This is equivalent to chaining if x % 2 == 0 and x % 3 == 0. Two separate if clauses or one combined and work the same.

How do I write a dict comprehension?

Same syntax as a list comprehension but with key: value and curly braces:

squares = {x: x*x for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

You can also build a dict from two parallel lists:

keys = ["a", "b", "c"]
values = [1, 2, 3]
d = {k: v for k, v in zip(keys, values)}

How do I write a set comprehension?

Same syntax, just use curly braces with no colon:

unique_letters = {c for c in "abracadabra"}
# {'a', 'b', 'c', 'd', 'r'}

Can list comprehensions be nested?

Yes. The outer loop is written first. To flatten a 2D list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

Reading order is "for each row in matrix, for each num in row." Beyond two levels, write a regular nested loop — readability wins over cleverness.

Why does my list comprehension return None?

You're probably using a function that mutates in place and returns None. The classic trap:

result = [lst.append(x*2) for x in nums]   # Wrong — list.append returns None

list.append() modifies and returns None, so you get a list of Nones. Either use an expression that returns a value ([x*2 for x in nums]) or write a normal for loop.

Can I use else in a list comprehension without if?

No — else requires an if first. The two forms are different:

  • Filter (after the loop): [x for x in nums if x > 0]else is illegal here.
  • Transform (before the loop): [x if x > 0 else 0 for x in nums]if/else together act as a conditional expression.

Want to run these comprehensions? The Python playground runs Python in your browser — no install, no signup.

Want to learn more?

Explore free chapter-wise notes with quizzes and code playground

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube