← All concepts

Lecture 3

for loops and range()

A for loop runs the same lines once for every item.

Once per item

The indented lines run once for each item, with the loop variable set to that item. Two patterns come up again and again: a running total that starts at 0, and a new list that starts empty.

total = 0
doubled = []
for v in [2, 3, 5]:
total += v
doubled.append(v * 2)
print(total, doubled)

Output

10 [4, 6, 10]

range()

range(stop) counts from 0 up to — not including — stop. range(start, stop, step) changes where it starts and how far it jumps.

print(list(range(4)))
print(list(range(2, 6)))
print(list(range(0, 10, 3)))

Output

[0, 1, 2, 3]
[2, 3, 4, 5]
[0, 3, 6, 9]

break

break leaves the loop straight away; the loop variable keeps its last value.

for v in [3, 8, 2, 9]:
if v > 5:
break
print(v)

Output

8

Going further

From the advanced notebook — this is what the advanced questions test.

enumerate() and zip()

enumerate() gives each position together with its item. zip() walks two lists side by side.

for i, b in enumerate("GAT"):
print(i, b)
for a, b in zip([1, 2], [10, 20]):
print(a * b)

Output

0 G
1 A
2 T
10
40

List comprehensions

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

print([x * x for x in range(5)])

Output

[0, 1, 4, 9, 16]

while loops

A while loop repeats as long as its condition is True — use it when you do not know in advance how many runs you need.

n = 1
steps = 0
while n < 100:
n = n * 3
steps += 1
print(n, steps)

Output

243 5