Ravindra BagaleCourses & study guides मराठी Track your progress

Python for Loops and while Loops Explained with Examples (range, break, continue)

P6.7 Python List Comprehension Explained Simply

Why. The "empty list + loop + append" pattern is so common that Python has a one-line form.

What. [expression for item in list if condition] builds a new list in one line.

How.

Turn a loop into a comprehension

  1. Write the value you want first.
  2. Then for item in list.
  3. Optionally add if condition at the end.
  4. Wrap everything in [ ].

Worked example A — Convert prices in one line.

Step 1 — What we do. Same dollar to rupee example as before.

Step 2 — Type and run this code.

usd = [10, 25, 40]
inr = [p * 83 for p in usd]
print(inr)

Step 3 — Output you should see.

[830, 2075, 3320]

Step 4 — What it means. Same result as the 4-line loop.

Worked example B — Filter in one line.

Step 1 — What we do. Keep orders above ₹500.

Step 2 — Type and run this code.

orders = [250, 800, 1200, 300, 650]
print([o for o in orders if o > 500])

Step 3 — Output you should see.

[800, 1200, 650]

Step 4 — What it means. The if at the end filters.

Worked example C — Clean names in one line.

Step 1 — What we do. Clean a list of messy city names.

Step 2 — Type and run this code.

raw = ["  pune", "MUMBAI ", "nagpur"]
print([c.strip().title() for c in raw])

Step 3 — Output you should see.

['Pune', 'Mumbai', 'Nagpur']

Step 4 — What it means. Comprehension plus string methods = quick cleaning.

Ravindra Bagale's Tip

Use comprehensions for short, simple jobs. If you need more than one if, write a normal loop.

Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.