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
- Write the value you want first.
- Then
for item in list. - Optionally add
if conditionat the end. - 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.
Ravindra Bagale's Tip – मराठी
छोट्या, सोप्या कामांसाठी comprehensions वापरा. एकापेक्षा जास्त if लागले तर साधा loop लिहा.
Ravindra Bagale's Tip – हिंदी
छोटे, आसान कामों के लिए comprehensions इस्तेमाल करो. एक से ज़्यादा if चाहिए तो सादा loop लिखो.
Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.