Python Tutorial
Python Loop Lists
Loop through a list with for, while, or list comprehension.
for Loop
Print each item.
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
for i in range(len(thislist)):
print(thislist[i])while Loop
Use an index and increment it until you reach len(list).
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i += 1📘 Real-World Deep Dive
The <code>for</code> loop is the workhorse for iterating lists — with the right idiom (<code>enumerate</code>, parallel iteration, comprehension form) you save boilerplate and avoid off-by-one bugs.
Real-Life Scenario
Walk two parallel lists of timestamps and prices, build a tidy table including a running average — without index arithmetic.
Real-Life Example
import csv, io
timestamps = ["09:00", "10:00", "11:00", "12:00", "13:00"]
prices = [101.5, 102.7, 100.9, 99.4, 100.0]
print(f"{'time':<6} {'price':>8} {'avg_so_far':>10}")
running_sum = 0.0
for i, (ts, px) in enumerate(zip(timestamps, prices), start=1):
running_sum += px
avg = running_sum / i
print(f"{ts:<6} {px:>8.2f} {avg:>10.2f}")
# Comprehension form for the table:
rows = [(ts, px, sum(prices[:i+1]) / (i + 1)) for i, (ts, px) in enumerate(zip(timestamps, prices))]
print("rows:", rows)Expected Output
time price avg_so_far
09:00 101.50 101.50
10:00 102.70 102.10
11:00 100.90 101.70
12:00 99.40 101.13
13:00 100.00 101.04
rows: [('09:00', 101.5, 101.5), ..., ('13:00', 100.0, 101.04)]Common mistakes
- Building the running-avg with
sum(prices[:i+1])is O(n²); prefer a running accumulator. range(len(xs))is rarely what you want — useenumerate(xs)instead.- Tuples unpacked in
for ... inhave to match exactly; one too few or too many raisesValueError.
🚀 Performance & Best Practices
enumerate(start=1)lets you writei+1-less windowed computations.itertools.tee+islicefor sliding windows; avoid per-iteration slicing on big lists.- Comprehensions beat
for+appendfor the same task — both in clarity and speed.
🧪 Try It Yourself
- Write
pair_diff(xs, ys)that returns the elementwise difference of two zipped lists. - Replace the running-sum example with a
itertools.accumulateone-liner. - Benchmark a
forloop against a comprehension for this example.