for Loops and range()
Unit ID: M04-U03 Estimated active time: 25-35 minutes
Process each item
module_titles = ["Values", "Collections", "Control flow"]
for title in module_titles:
print(title)
On each iteration, title refers to the next list item. The indented block runs once per item.
Use a singular loop name for items from a plural collection. for record in records is clearer than for x in data.
Transform into a new list
clean_titles = []
for title in module_titles:
clean_title = title.strip().title()
clean_titles.append(clean_title)
The source list remains unchanged. The result list records each transformed value.
Use range for a numeric sequence
for number in range(1, 4):
print(number)
Output:
1
2
3
The stop value 4 is excluded. range(start, stop, step) follows the same stop-excluded idea as slicing.
Use enumerate when position matters
for position, title in enumerate(module_titles, start=1):
print(position, title)
This produces human-friendly positions starting at 1 without manually changing a counter.
Do not change list length while iterating over it
Removing items from the same list being traversed can skip values or create confusing results. Build a new result list or iterate over a copy.
scores = [8, -1, 6, 11]
valid_scores = []
for score in scores:
if type(score) is int and 0 <= score <= 10:
valid_scores.append(score)
Practice
Given hours = [8, 12, 0, 45, "6"], build separate valid_hours and invalid_hours lists using a for loop. Valid hours must have exact type int and be from 0 to 40.
Expected valid values: [8, 12, 0].
Takeaway
A for loop makes repeated processing explicit. Build new result collections instead of mutating the source while traversing it. Next, we will use while for repetition controlled by a changing condition.
