Start.dev
Back to blog

Python for loops explained, with real examples

Learn Python for loops step by step: loop over lists, strings and dictionaries, count with range(), use enumerate, break and continue, and avoid common mistakes.

Ariel Weinberger
Ariel Weinberger ยท 6 min read

How do you run the same code for every item in a list without writing it out again and again?

Short answer: use a for loop. for item in things: runs the indented block once for each item, and item holds the current one each time.

fruits = ["apple", "banana", "cherry"]
 
for fruit in fruits:
    print(fruit)
apple
banana
cherry

By the end of this post you will be able to loop over lists, strings and dictionaries, count with range(), get an index with enumerate(), stop or skip with break and continue, and avoid the mistakes that trip up most beginners. Every example runs as is.

How a for loop works

Every for loop has the same shape:

for name in collection:
    # this block runs once per item

Three details matter:

  • name is a variable you choose. Python sets it to the next item at the start of each pass. Pick a name that says what one item is: fruit, price, user.
  • The colon at the end of the first line is required.
  • The indented block is the body. Everything indented under the for line runs on each pass. The first line that isn't indented runs once, after the loop finishes.

In the fruit example, the body runs three times. First fruit is "apple", then "banana", then "cherry". Introduction To Loops (opens in a new tab) walks through this step by step.

Doing something useful: a running total

Printing each item is a start. Most real loops build up a result. Here is a total for a shopping cart:

prices = [4.5, 12.0, 3.25]
total = 0
 
for price in prices:
    total += price
 
print(total)  # 19.75

total starts at 0 outside the loop. Each pass adds one price. The print isn't indented, so it runs once, after the last price has been added.

The same pattern counts things. How many orders were over 10?

orders = [8, 15, 22, 5, 12]
big_orders = 0
 
for amount in orders:
    if amount > 10:
        big_orders += 1
 
print(big_orders)  # 3

See Looping Over Lists (opens in a new tab).

Counting with range()

Sometimes you don't have a list. You just want to repeat something a set number of times, or loop over numbers. That is what range() is for.

for i in range(5):
    print(i)
0
1
2
3
4

range(5) gives you five numbers, starting at 0 and stopping before 5. That "stops before" rule catches everyone at first.

range() takes up to three numbers:

CallNumbers you getMeaning
range(5)0, 1, 2, 3, 4Start at 0, stop before 5
range(1, 6)1, 2, 3, 4, 5Start at 1, stop before 6
range(0, 10, 2)0, 2, 4, 6, 8Count up in steps of 2
range(5, 0, -1)5, 4, 3, 2, 1Count down

A countdown:

for seconds in range(3, 0, -1):
    print(seconds)
print("Go!")
3
2
1
Go!

Looping over a string

A string is a sequence of characters, so a for loop goes through it one letter at a time:

word = "banana"
vowels = 0
 
for letter in word:
    if letter in "aeiou":
        vowels += 1
 
print(vowels)  # 3

See Looping Through Strings (opens in a new tab).

Looping over a dictionary

Looping over a dictionary directly gives you its keys. Use .items() to get each key and value together:

scores = {"Ana": 90, "Ben": 75, "Cleo": 82}
 
for name, score in scores.items():
    print(f"{name}: {score}")
Ana: 90
Ben: 75
Cleo: 82

name, score unpacks each pair into two variables. Looping Dictionaries (opens in a new tab) covers .keys(), .values() and .items().

Getting the position with enumerate()

When you need both the item and its position, use enumerate():

fruits = ["apple", "banana", "cherry"]
 
for position, fruit in enumerate(fruits, start=1):
    print(f"{position}. {fruit}")
1. apple
2. banana
3. cherry

start=1 makes the numbering begin at 1 instead of 0, which is what you want for a list people will read. See Enumerate (opens in a new tab).

Stopping early with break, skipping with continue

break ends the loop immediately. Use it when you have found what you were looking for:

temperatures = [12, 15, -3, 8, -1]
 
for temp in temperatures:
    if temp < 0:
        print(f"First freezing reading: {temp}")
        break
First freezing reading: -3

The loop never looks at 8 or -1. It stopped at the first match.

continue skips the rest of the current pass and moves on to the next item:

for temp in temperatures:
    if temp < 0:
        continue
    print(temp)
12
15
8

See Break (opens in a new tab) and Continue (opens in a new tab).

Loops inside loops

You can put a loop inside another loop. The inner loop runs completely for each pass of the outer one:

for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end=" ")
    print()
1 2 3 
2 4 6 
3 6 9 

end=" " keeps the numbers on one line, and the empty print() starts a new line after each row. Nested Loops (opens in a new tab) has more.

for vs while

Python has a second loop, while, which keeps going as long as a condition is true. Use for when you know what you are looping over: a list, a string, a range. Use while when you don't know how many passes you need, like asking for input until it is valid. While Loops (opens in a new tab) covers it.

Common mistakes

  • Forgetting the colon or the indent. for fruit in fruits without a colon is a SyntaxError. A body that isn't indented gives an IndentationError.

  • Off by one with range(). range(1, 10) stops at 9. If you want 1 to 10, write range(1, 11).

  • Changing a list while you loop over it. Removing items as you go skips some:

    nums = [1, 2, 2, 3]
    for n in nums:
        if n == 2:
            nums.remove(n)
    print(nums)  # [1, 2, 3], one 2 is still there

    Build a new list instead: nums = [n for n in nums if n != 2] gives [1, 3]. That one-liner is a list comprehension, which Python list comprehensions explained covers.

  • Using range(len(items)) when you don't need the index. for item in items: is shorter and clearer. If you need the index too, use enumerate().

  • Putting the result inside the loop. If print(total) is indented, it prints after every item instead of once at the end.

Quick recap

  • for item in collection: runs the indented block once per item.
  • range(stop), range(start, stop) and range(start, stop, step) give you numbers, always stopping before stop.
  • Loop over strings letter by letter, and over dictionaries with .items().
  • enumerate() gives you the position and the item together.
  • break stops the loop. continue skips to the next item.

Frequently asked questions

What is a for loop in Python?

It is a way to run the same block of code once for each item in a collection, like a list, a string or a range of numbers. The loop variable holds the current item on each pass.

How do I loop a specific number of times in Python?

Use range(). for i in range(10): runs the body 10 times, with i going from 0 to 9. If you don't need the number, the convention is to name it _, as in for _ in range(10):.

How do I get the index in a Python for loop?

Use enumerate(). for index, item in enumerate(items): gives you both. Add start=1 if you want counting to begin at 1.

What is the difference between break and continue?

break ends the whole loop right away. continue ends only the current pass and moves on to the next item.

What is the difference between a for loop and a while loop?

A for loop goes through a known collection, item by item. A while loop keeps running as long as a condition stays true, so it fits cases where you don't know in advance how many passes you need.

Practice

The matching exercises are in the course. Start with Looping Over Lists (opens in a new tab), search a list in Finding Values (opens in a new tab), then put it together in Loops In Practice (opens in a new tab). Each exercise runs Python in your browser, so there is nothing to install.

Keep going

Python for Beginners (opens in a new tab) takes you from your first print() to loops, functions, dictionaries and classes. Once loops feel natural, Intermediate Python (opens in a new tab) shows the shortcuts, like enumerate(), zip() and list comprehensions.

Level up your coding skills

Jump into interactive courses and start building real-world projects.

Start learning

Related posts

Turn a for loop that builds a new list into one line. You will curve scores, keep the ones that pass, and fix the syntax error beginners hit.
Ariel Weinberger
Ariel Weinberger ยท 8 min read
Python lists, tuples and dictionaries compared with simple examples: how each one works, how they differ, and a quick rule for picking the right one.
Ariel Weinberger
Ariel Weinberger ยท 4 min read
A day-by-day Python roadmap for your first 30 days: what to learn, what to build each week, and the mistakes that stall most beginners.
Ariel Weinberger
Ariel Weinberger ยท 7 min read