New to Rust? Grab our free Rust for Beginners eBook Get it free →
Python for loop: syntax, break, continue and range() examples

The Python for loop syntax lets you run a block of code once for each item in a sequence, whether that’s a list, a string, a range or a dictionary. Every dev reaches for it in almost every script they write, from quick print statements to processing rows from a file. This guide covers the core syntax, walks through range(), nested loops, break, continue, else and enumerate(), and flags the mistakes that trip up most beginners early on.
Python for loop
A control flow statement that enables the iteration over a sequence until all items in the sequence have been processed is called as for loop. This allows you to execute a block of code for each item in the sequence. The iteration ends based on the completion of iterating through all the items in the sequence. The capabilities of the for loop extends towards iterating a large number of entities such as string or lists or tuples.
Syntax of for loop
The for loop can be coded using a couple of syntaxes, each given below.
Syntax 1:
for val1 in val2:
<statement block>
Syntax 2:
for val in range (<startvalue>, <endvalue>, <jumps>):
<statement block>
The latter syntax harnesses the potential of the range function which makes it easier to specify the boundaries within which the for loop ought to operate. It also provides the flexibility for specifying the increments at which the iterations are to be executed.
Syntax 3:
for val1 in val2:
for val3 in val4:
<statement block>
<statement block>
Some might have guessed it by now. The above is the representation of the nested for loop. These are iterations within iterations such that the result obtained by ‘x’ iterations of the innermost condition would then be fed as an input for the ‘y’ iterations of the outermost condition.
Examples of using for loop
This section shall detail the different variations in which the standard for loop could be utilised in Python. Let us get started with how to use it with a list.
Example 1:
Given below is a list, each of whose elements is to be incremented by one using the for loop.
ar1 = [20, 57, -10, 89]
for i in ar1:
print(i+1)
Output:

Example 2:
Not only numbers but also strings can be iterated through for loop. In the below code, let us have a look at how a list of string is iterated using a for loop.
snacks = ["Samosa", "Chips", "Murukku"]
for i in snacks:
print(i)
Output:

Example 3:
In both examples, we have mentioned ‘i’ after for, which represents each entity within the list that is to be put through the loop. Now let us have a look at how a for loop and the range function can be put to work together. The below code feeds the data within which the iteration is to be carried out using the range function. It states that the data shall start from ‘1’ and end at ’90’ in increments of ’10’.
for i in range(1,90,10):
print(i/2)
Output:

Example 4:
Finally, let us get on with the workings of a nested for loop through the below code. Here the numbers from the range specified in the first for loop will be printed the same number of counts they stand for (i.e.) the number ‘2’ gets printed 2 times & so on & so forth.
for i in range(2,9,2):
for j in range(i):
print(i, end = ' ')
print()
Output:

Looping through dictionaries, tuples and sets
The examples above cover lists, strings and ranges, but a for loop works on any iterable, so dictionaries, tuples and sets are all fair game too. Each one behaves a little differently once you drop it into a loop, and knowing the difference saves you a debugging session later.
Looping through a dictionary
A plain for key in my_dict: only gives you the keys. To get both the key and the value in one pass, call .items().
prices = {"coffee": 3, "tea": 2, "juice": 4}
for item, cost in prices.items():
print(f"{item} costs ${cost}")
This pattern comes up constantly once you start working with the dictionary data structure in real code, whether you’re reading config values or summing up totals from an API response.
Looping through a tuple
Tuples loop exactly like lists since both are ordered sequences. The only real difference is that you can’t reassign items inside the loop, since tuples are immutable.
coordinates = (10, 20, 30)
for value in coordinates:
print(value)
Looping through a set
Sets have no fixed order, so a for loop over a set will visit every item but not in the order you added them. This is fine for tasks like deduplication where order doesn’t matter.
unique_ids = {101, 102, 103, 101}
for user_id in unique_ids:
print(user_id)
Notice the repeated 101 in the set literal collapses to one value. That’s the same membership check a for loop relies on internally to know where each sequence ends.
Using the range() function in Python for loop syntax
Example 3 above already used range() with three arguments, but it’s worth breaking down all three forms since this is where most beginners get an off-by-one surprise.
range(stop)
A single argument starts the count at 0 and stops one short of the number you give it.
for i in range(5):
print(i)
# prints 0, 1, 2, 3, 4
range(start, stop)
Two arguments let you pick where counting begins.
for i in range(2, 6):
print(i)
# prints 2, 3, 4, 5
range(start, stop, step)
The third argument controls the increment, and it can be negative to count downward.
for i in range(10, 0, -2):
print(i)
# prints 10, 8, 6, 4, 2
range() doesn’t build the whole list of numbers in memory up front. It produces each value on demand, so range(1_000_000) costs almost nothing until you actually loop over it.
Loop control statements: break, continue and pass
Python gives you three keywords for changing how a for loop behaves mid-run. Each one solves a different problem, and mixing them up is a common source of logic bugs.
The break statement
break exits the loop immediately, skipping every remaining item. Pair it with an if statement so you only exit when a condition shows up.
scores = [72, 88, 45, 91, 60]
for score in scores:
if score < 50:
print("Found a failing score, stopping check")
break
print(f"Score {score} is fine")
The continue statement
continue skips the rest of the current iteration and moves straight to the next item, without leaving the loop.
numbers = [1, 2, 3, 4, 5, 6]
for n in numbers:
if n % 2 != 0:
continue
print(f"{n} is even")
The pass statement
pass does nothing at all. It exists because Python won’t let you leave a code block empty, so it’s a placeholder you use while sketching out logic you haven’t written yet.
for n in range(5):
if n == 3:
pass
print(n)
You’ll see the exact same pattern when stubbing out the body of a function you haven’t written yet, since Python enforces the same rule there.
The else clause in a for loop
Python lets you attach an else block to a for loop, and it only runs if the loop finishes every iteration without hitting a break. This trips people up the first time they see it, since else usually implies “the opposite case” everywhere else in the language. It only makes sense to add one when the loop also contains a break, since a for loop with no break will always reach the else block anyway.
def find_prime_factor(n):
for i in range(2, n):
if n % i == 0:
print(f"{n} has a factor: {i}")
break
else:
print(f"{n} is prime")
find_prime_factor(17)
find_prime_factor(18)
Here the else block prints “17 is prime” because the loop never broke. For 18, the loop finds a factor and breaks so the else block gets skipped entirely. It’s a clean way to write a search-then-fallback pattern without a separate flag variable.
Using enumerate() to get the index and the value
Sometimes you need the position of an item as well as its value, and writing range(len(my_list)) to get there is a sign you’re fighting the language instead of using it. enumerate() wraps any sequence and gives you both the index and the value directly, in one clean pass through the loop.
languages = ["Python", "Rust", "Go"]
for index, name in enumerate(languages):
print(f"{index}: {name}")
You can also set a custom starting number if your display should start from 1 instead of 0. This comes up often when numbering a printed list for a user, since counting from 0 usually looks wrong on screen even though it’s the natural choice internally.
for index, name in enumerate(languages, start=1):
print(f"{index}: {name}")
Under the hood, enumerate() builds a sequence of (index, value) pairs rather than two separate values, so the two variables on the left of the for loop are unpacking a small tuple each time round.
Common for loop patterns
A handful of patterns show up again and again once you’ve written enough for loops. Recognizing them makes your code shorter and easier to read.
The accumulator pattern
Start a variable at zero (or empty), then update it once per iteration. This is how you build totals, running sums or combined strings.
prices = [12.50, 8.00, 21.75]
total = 0
for price in prices:
total += price
print(f"Total: ${total:.2f}")
Looping in reverse with reversed()
Wrap any sequence in reversed() to walk through it back to front without rewriting your range() bounds.
countdown = [3, 2, 1, 0]
for n in reversed(countdown):
print(n)
Iterating two lists at once with zip()
zip() pairs up items from two or more sequences so you can loop over them in step, instead of indexing into each one separately.
names = ["Alice", "Bob", "Carol"]
scores = [88, 92, 79]
for name, score in zip(names, scores):
print(f"{name}: {score}")
When to use a list comprehension instead
If your entire loop body exists just to build a new list, a list comprehension usually says the same thing in one line. It’s worth knowing both forms, since comprehensions replace a lot of short for loops in real codebases.
squares = []
for n in range(6):
squares.append(n * n)
# same result, one line
squares = [n * n for n in range(6)]
For loop vs while loop in Python
The for loop and the while loop both repeat code, but they answer different questions. A for loop is the right tool when you already know the sequence you’re iterating over, a list, a range, a file’s lines. A while loop is the right tool when you’re waiting on a condition to change and don’t know in advance how many times that will take.
# for loop: known sequence
for attempt in range(3):
print(f"Attempt {attempt}")
# while loop: unknown duration
attempt = 0
while attempt < 3:
print(f"Attempt {attempt}")
attempt += 1
Both loops above print the same three lines, but the while version needs you to manage the counter yourself. That’s the trade-off: for loops handle the bookkeeping, while loops give you full control over when to stop.
Common for loop mistakes and errors
Most for loop bugs come from a small set of repeat offenders. Here are the ones I see most often.
IndentationError from inconsistent spacing
Python uses indentation to mark the loop body, so mixing tabs and spaces, or indenting a line by a different amount than its neighbors, raises an IndentationError before your code even runs.
for i in range(3):
print(i)
print("done")
# IndentationError: unindent does not match any outer indentation level
Modifying a list while looping over it
Adding or removing items from a list while a for loop is iterating over it skips items or throws off the count, since the loop is tracking a position in a list that’s changing shape underneath it.
# risky: mutates the list mid-loop
nums = [1, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
# safer: loop over a copy instead
nums = [1, 2, 3, 4]
for n in nums[:]:
if n % 2 == 0:
nums.remove(n)
Looping with range(len(list)) instead of the list itself
for i in range(len(my_list)): print(my_list[i]) works, but it’s usually unnecessary. If you don’t need the index, loop over the list directly. If you do need the index, reach for enumerate() instead.
fruits = ["apple", "banana", "cherry"]
# unnecessary
for i in range(len(fruits)):
print(fruits[i])
# direct and clearer
for fruit in fruits:
print(fruit)
A practical example: calculating a cart total with a for loop
Here’s how these pieces come together in something closer to real code. Say you have a shopping cart as a list of dictionaries, and you want the total cost after a discount on any item over $50.
cart = [
{"item": "Headphones", "price": 60},
{"item": "Notebook", "price": 5},
{"item": "Monitor", "price": 220},
]
total = 0
for product in cart:
price = product["price"]
if price > 50:
price = price * 0.9
total += price
print(f"{product['item']}: ${price:.2f}")
print(f"Cart total: ${total:.2f}")
This loop combines the accumulator pattern with dictionary access and an if statement, which is roughly what a real checkout function would look like before you add error handling around it. If you’re looping over rows in a pandas DataFrame instead of a plain list, the mechanics change since you’d typically use a method built for that rather than a raw for loop.
Key Takeaways
- for var in sequence: runs the block once per item, no manual index setup.
- range(start, stop, step) builds counted loops and generates values on demand.
- break exits a loop early, continue skips ahead to the next item.
- else on a for loop only runs if the loop finishes without a break.
- enumerate() hands you the index and value together in one pass.
- Nested loops run the inner loop completely for every outer iteration.
- range(len(list)) is usually a sign to loop over the list directly instead.
- Comprehensions replace many short for loops that only build a new list.
Frequently asked questions
What is the basic syntax of a for loop in Python?
Write for variable in sequence: followed by an indented code block. Python runs that block once for each item in the sequence, in order.
How do I loop a fixed number of times in Python?
Use for i in range(n): to run the loop body exactly n times, with i counting up from 0 to n - 1.
What’s the difference between break and continue in a for loop?
break exits the loop completely and skips every remaining item. continue skips only the current item and moves on to the next iteration.
Can I loop through a dictionary’s keys and values at once?
Yes, call .items() on the dictionary inside the for loop, like for key, value in my_dict.items():, to get both in each iteration.
How do I get the index of each item while looping over a list?
Wrap the list in enumerate(), as in for index, item in enumerate(my_list):, instead of manually tracking a counter variable.
Why did my for loop’s else block not run?
The else block on a for loop is skipped whenever the loop exits through a break statement. It only runs when the loop finishes all its iterations normally.
Should I use a for loop or a while loop for user input?
Use a while loop, since you don’t know in advance how many attempts a user will need. For loops fit sequences you already know the length of.




