Python

Python List Comprehension, 15 Examples for CBSE Students

Learn Python list comprehension with 15 practical examples. CBSE Class 11 and 12 guide covering syntax, conditions, nested loops 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.

Want to learn more?

Explore free chapter-wise notes with quizzes and code playground

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube