List Comprehension

  • This lesson teaches how to create lists using a single line of code with list comprehension.

  • List comprehension is a short and powerful way to create a new list from an existing list (or iterable) in a single line of code.

    Instead of writing long loops, Python allows us to write clean, readable, and compact code.

    👉 It combines:

    • Loop

    • Condition (optional)

    • Expression

    into one line.

    Basic Syntax

    new_list = [expression for item in iterable if condition]

    Simple Meaning

    List comprehension means:

    “Take each item, do something with it, and store the result in a new list.”=

Daily Life Example

Imagine a teacher has marks of students and wants a list of only passed students (marks ≥ 35).

marks = [20, 45, 60, 10, 75, 30]
passed = []
for m in marks:
    if m >= 35:
        passed.append(m)
print(passed)

Using List Comprehension:

marks = [20, 45, 60, 10, 75, 30]
passed = [m for m in marks if m >= 35]
print(passed)

Square Numbers

squares = [x*x for x in range(1, 6)]
print(squares)

Even Numbers Only

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = [n for n in numbers if n % 2 == 0]
print(evens)

Convert Names to Uppercase

names = ["amit", "riya", "rahul"]
upper_names = [name.upper() for name in names]
print(upper_names)

Filter Words Longer Than 4 Letters

words = ["pen", "notebook", "bag", "calculator"]
long_words = [w for w in words if len(w) > 4]
print(long_words)

List Comprehension Without Condition

nums = [1, 2, 3]
double = [n*2 for n in nums]
print(double)

List Comprehension With Condition

nums = [1, 2, 3, 4, 5]
odd = [n for n in nums if n % 2 != 0]
print(odd)
  • Why Use List Comprehension?

    •  Makes code short

    • Improves readability

    • Faster than normal loops

    • Used in real-world Python programs