Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟢 Beginner  ·  Lesson 16

List Comprehension in Python

In this lesson: Write one-line loops with list comprehension in Python — filters, if-else, nested — compared with normal loops.

What is a comprehension?

A comprehension builds a new list, set or dictionary from existing data in one readable line. It replaces the common pattern “create an empty list → loop → append”.

Python – loop_vs_comprehension.py
prices = [120, 450, 80, 999]

# normal loop
with_gst = []
for p in prices:
    with_gst.append(round(p * 1.18))
print(with_gst)

# list comprehension – same result
with_gst = [round(p * 1.18) for p in prices]
print(with_gst)
[142, 531, 94, 1179] [142, 531, 94, 1179]

Read it like English: [ expression for item in iterable if condition ] → “make expression for every item in iterable that passes condition”.

Filtering with if

Python – filter.py
marks = {"Asha": 91, "Ravi": 58, "Neha": 76, "Kabir": 34, "Isha": 88}

passed = [name for name, m in marks.items() if m >= 40]
toppers = [name for name, m in marks.items() if m >= 85]
print("Passed :", passed)
print("Toppers:", toppers)
Passed : ['Asha', 'Ravi', 'Neha', 'Isha'] Toppers: ['Asha', 'Isha']

if-else inside the expression

To choose between two values (not to filter), put if … else … before for.

Python – if_else.py
marks = [91, 58, 76, 34, 88]

result = ["Pass" if m >= 40 else "Fail" for m in marks]
grades = ["A" if m >= 85 else "B" if m >= 60 else "C" if m >= 40 else "F" for m in marks]
print(result)
print(grades)
['Pass', 'Pass', 'Pass', 'Fail', 'Pass'] ['A', 'C', 'B', 'F', 'A']
PositionPurposeExample
if after forKeep only some items (filter)[m for m in marks if m >= 40]
if … else before forTransform every item into one of two values["P" if m >= 40 else "F" for m in marks]

Dictionary comprehension

Python – dict_comprehension.py
items = ["kaju katli", "ghewar", "rasmalai"]
price = [900, 650, 700]

menu = {name.title(): p for name, p in zip(items, price)}
print(menu)

discounted = {k: round(v * 0.9) for k, v in menu.items() if v > 680}
print(discounted)

# swap keys and values
by_price = {v: k for k, v in menu.items()}
print(by_price[650])
{'Kaju Katli': 900, 'Ghewar': 650, 'Rasmalai': 700} {'Kaju Katli': 810, 'Rasmalai': 630} Ghewar

Set comprehension

Python – set_comprehension.py
emails = ["riya@gmail.com", "AMAN@yahoo.com", "neha@gmail.com", "aman@yahoo.com"]

domains = {e.split("@")[1].lower() for e in emails}
unique_users = {e.lower() for e in emails}
print(sorted(domains))
print(len(emails), "emails,", len(unique_users), "unique")
['gmail.com', 'yahoo.com'] 4 emails, 3 unique

Nested loops and flattening

Python – nested.py
sections = [["Asha", "Ravi"], ["Neha"], ["Kabir", "Isha", "Om"]]

# loops are written in the same order as normal nested for-loops
all_students = [s for section in sections for s in section]
print(all_students)

table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
for row in table:
    print(row)
['Asha', 'Ravi', 'Neha', 'Kabir', 'Isha', 'Om'] [1, 2, 3] [2, 4, 6] [3, 6, 9]
⚠️ Keep it readable

If a comprehension needs more than two for parts or a long condition, write a normal loop. Clear code is better than clever code.

Real example: clean a messy student list

Python – clean_names.py
raw = ["  asha sharma ", "RAVI kumar", "", "neha  verma", "  ", "Kabir Singh"]

clean = [" ".join(name.split()).title() for name in raw if name.strip()]
initials = {name: "".join(part[0] for part in name.split()) for name in clean}

print(clean)
print(initials)
['Asha Sharma', 'Ravi Kumar', 'Neha Verma', 'Kabir Singh'] {'Asha Sharma': 'AS', 'Ravi Kumar': 'RK', 'Neha Verma': 'NV', 'Kabir Singh': 'KS'}

Is a comprehension faster?

Python – speed.py
import timeit

loop_code = """
result = []
for n in range(10000):
    result.append(n * 2)
"""
comp_code = "result = [n * 2 for n in range(10000)]"

t_loop = timeit.timeit(loop_code, number=300)
t_comp = timeit.timeit(comp_code, number=300)
print("comprehension faster:", t_comp < t_loop)
comprehension faster: True

Usually yes, by about 20–40%, because the append happens inside optimised C code. But choose comprehensions mainly for readability; for side effects such as printing or saving, use a normal loop.

Common mistakes

MistakeFix
[x for x in data if x > 0 else 0] → SyntaxErrorMove if-else before for: [x if x > 0 else 0 for x in data]
Using a comprehension only to print: [print(x) for x in data]Use a normal for loop
Very long nested comprehensionSplit into a loop or helper function
Expecting (x for x in data) to be a tupleIt is a generator; use tuple(...)

Practice tasks

  1. From a list of numbers make a list of their cubes, keeping only odd numbers.
  2. From {"pen": 10, "book": 250, "bag": 799} make a new dictionary with 18% GST added.
  3. Make a set of all vowels that appear in a sentence.
  4. Flatten [[1, 2], [3], [4, 5, 6]] and keep only even numbers.

Summary

  • [expr for x in data if cond] builds a list; {k: v for …} a dictionary; {expr for …} a set.
  • if after for filters; if/else before for chooses a value.
  • Multiple for parts follow normal nested-loop order.
  • Prefer readability: switch to a loop when it gets complicated or has side effects.

Frequently Asked Questions

Is there a tuple comprehension in Python?
No. (x for x in data) creates a generator expression. To get a tuple write tuple(x for x in data).
Can I use else without if-else in a comprehension?
No. A filter uses only if after for. else is allowed only as part of a conditional expression written before for.
Do comprehension variables leak outside?
No. In Python 3 the loop variable of a comprehension stays inside it, unlike a normal for loop whose variable remains after the loop.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicModules and Packages Your progress: 16 / 66 (24%) · Lesson 17 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free