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

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

P6.4 How to Build a New List Inside a Loop

Why. Often you transform data: convert all prices, keep only some rows. You collect results into a new list.

What. Start with an empty list [], then append inside the loop.

How.

Collect results

  1. Make an empty list before the loop.
  2. Inside the loop, calculate the new value.
  3. append it to the list.
  4. Print the list after the loop.

Worked example A — Convert dollars to rupees.

Step 1 — What we do. Prices in USD for an IT company; rate ₹83 per $.

Step 2 — Type and run this code.

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

Step 3 — Output you should see.

[830, 2075, 3320]

Step 4 — What it means. Each converted price is added to the new list.

Worked example B — Keep only some items.

Step 1 — What we do. We keep only orders above ₹500.

Step 2 — Type and run this code.

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

Step 3 — Output you should see.

[800, 1200, 650]

Step 4 — What it means. This is filtering. In pandas, df[df.amount > 500] does the same.

Ravindra Bagale's Tip

Do not change a list while looping over it. Build a new list instead.