A for loop visits each item in an iterable, one at a time. Strings, lists, tuples, dictionaries, sets, and ranges are all iterable.
names = ["Ada", "Grace", "Linus"]
for name in names:
print(f"Hello, {name}!")Hello, Ada! Hello, Grace! Hello, Linus!
The loop variable (name) is assigned to the next item on each iteration. It remains available after the loop, but relying on that is usually a mistake.
Iterating over a string#
word = "Python"
for letter in word:
print(letter)Each character is a one-character string.
Counted repetition#
for number in range(5):
print(number)0 1 2 3 4
range(5) produces 0 through 4. See the next tutorial for start, stop, and step variations.
Accumulators#
numbers = [12, 7, 19, 4]
total = 0
for number in numbers:
total += number
average = total / len(numbers)
print(f"Average: {average:.2f}")Initialise the accumulator before the loop. Inside, update it with each item.
Building a new list#
numbers = [1, 2, 3, 4, 5, 6]
evens = []
for number in numbers:
if number % 2 == 0:
evens.append(number)
print(evens)A list comprehension expresses the same idea more compactly:
evens = [number for number in numbers if number % 2 == 0]Use a comprehension when it remains easy to read. Use a loop when the body needs several statements or logging.
Nested loops#
for row in range(1, 4):
for column in range(1, 4):
print(row * column, end=" ")
print()1 2 3 2 4 6 3 6 9
The inner loop completes all of its iterations for each single iteration of the outer loop.
Dictionaries#
Iterating over a dictionary yields its keys by default:
scores = {"Ada": 90, "Grace": 95}
for name in scores:
print(name, scores[name])Use .items() when you need both keys and values:
for name, score in scores.items():
print(f"{name}: {score}")Practice#
Given a list of temperatures, count how many are above 25 degrees and compute the average. Then rewrite the solution with a list comprehension for the warm days.
