A Python for loop runs an indented block once for each item in an iterable. Write for item in collection:, then indent the work for each item. A loop over a list gets the values directly. A loop over range(3) gets the integers 0, 1, and 2.
durations = [12, 7, 15]
total = 0
for duration in durations:
total += duration
assert total == 34
total = 0 runs once, before the loop starts. The body adds 12, then 7, then 15. Move the initial assignment into the body and it resets every time, leaving only 15. An empty list leaves the initial total at zero.
Loop over a list, string, or dictionary
A loop over a string receives characters. A loop over a list receives its items. A loop over a dictionary receives its keys. For dictionary keys and values together, use for key, value in mapping.items():. For sequence positions paired with values, use for index, value in enumerate(sequence):.
tasks = {"outline": "ready", "draft": "waiting", "review": "ready"}
ready = []
for task, status in tasks.items():
if status == "ready":
ready.append(task)
assert ready == ["outline", "review"]
The test runs for every task. The append sits one level deeper, so it runs only when the task is ready. Align the append with the if and the loop adds every task, including draft.
Use indexes for a reason
for i in range(len(items)): can help when you need neighboring positions in a list. Use for item in items: when the work only needs each item. If you need both, enumerate(items) gives you the position and value together.
If an index represents a line number printed for a human, enumerate(lines, start=1) is useful. That number is for display. Do not reuse it directly to index the same list unless you intended to shift the position. For an index into a slice, the count also belongs to the slice unless you deliberately offset it.
Stop or skip on purpose
continue skips the rest of the current iteration. break exits the nearest loop. A clear condition before either statement helps a reader know whether you are skipping one candidate or abandoning the whole search.
messages = ["", " ", "ready", "later"]
first_message = None
for message in messages:
cleaned = message.strip()
if not cleaned:
continue
first_message = cleaned
break
assert first_message == "ready"
The starting None makes the empty result deliberate. If the input has no usable message, the name still exists after the loop. Depending on a variable that was only assigned inside the body is risky when the iterable can be empty.
Avoid modifying the collection you are traversing
Removing entries by position during traversal can shift the next item out from under the iterator. Adding keys to a dictionary while iterating it can also fail. For a filter, create a fresh collection. For in-place updates that are required by the caller, decide ahead of time which positions or keys to change, then apply the changes in a separate pass.
A file or generator may produce values only once. A second loop over an already consumed iterator can be empty even though the first pass worked. If you need to process each item twice, make a fresh iterator from the source or save the relevant data when memory and privacy requirements permit.
Build the output that matches your question
A running total, a filtered list, and a lookup table all start with different empty values. A total starts at zero. A collection of accepted records starts with an empty list. A table keyed by an identifier starts with an empty dictionary. Making that choice consciously helps you recognize when the loop silently discards useful information.
Suppose an index associates a reading with a room. Assigning one value per room to a dictionary keeps only the latest value seen for that room. If the task is to compare every reading, keep several values per room instead. An index of lists makes that idea visible.
readings = [("East", 10), ("West", 6), ("East", 12)]
by_room = {}
for room, value in readings:
by_room.setdefault(room, []).append(value)
assert by_room == {"East": [10, 12], "West": [6]}
Each iteration adds exactly one observation to the output. The order of readings within each room follows the input order. If two room labels should be treated as equivalent, apply that normalization explicitly before using them as keys. If the reader needs to see every original spelling, also preserve the source label.
Use the loop's else clause for a completed search
A loop can have an else clause, which runs if the loop finishes without a break. This includes an empty iterable. That makes it useful for a search where the absence of a match has a clear meaning.
for shelf in ("A", "B"):
if shelf == "C":
result = f"Found {shelf}"
break
else:
result = "Shelf not found"
assert result == "Shelf not found"
The else is aligned with for. Moving it under if makes it run for each nonmatch, a very different rule. If the team reads a return-on-match more easily, a small search function can return inside the loop and return a missing result after it. Either form should make an empty input and an exhausted search understandable.
Check what leaves the loop
For the task dictionary above, the report should be an empty list if no task is ready. Verify that a waiting task is omitted and that two ready tasks keep their order. A dictionary cannot represent repeated task keys as separate entries. If repeated task names represent different jobs, use a list of records or key the dictionary by an ID.
Nested loops can multiply work quickly. If five categories each use a second loop over every row, the program may revisit the same rows five times. When you can group records during one pass, the code often becomes easier to audit as well as cheaper to run. Start with a clear loop, then change the structure only when the actual workload calls for it.
The form of the loop should match the kind of progress your task makes. A range of integers suits a fixed count. Enumerate pairs each item with a number when you need both in a message. A while loop fits work that ends when its state changes. Those alternatives describe the reason you repeat an operation, which makes the stopping rule easier to review.
If the task combines two input sequences, decide whether they must be the same length. The default zip ends when the shorter input runs out. With strict=True on Python 3.10 or later, a difference raises an error when iteration reaches the mismatch. Use that option when dropping unmatched records would hide a broken assumption.