Python for Loops Explained

A for loop runs a block of code once for each item in a list, string, dictionary, or range. Learn the syntax, range(), enumerate(), zip(), and the mistakes to avoid.

5 min read

A Python for loop runs a block of code once for each item in a sequence, such as a list, a string, or a range of numbers.

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

This prints each fruit on its own line. On the first pass fruit is "apple", on the second it is "banana", and on the third it is "cherry". When the list runs out, the loop ends.

The syntax

pythonpython
for variable in iterable:
    # block to repeat
  • variable is a name you choose. Python assigns it the next item before each pass.
  • iterable is anything Python can step through: a list, tuple, string, dictionary, set, range, or file.
  • The line ends with a colon, and the block is indented by four spaces.

Unlike the for loop in C or JavaScript, there is no counter to set up, test, and increase. Python hands you the items directly.

Loop a set number of times with range()

To repeat something a fixed number of times, loop over range():

pythonpython
for i in range(5):
    print(i)

This prints 0, 1, 2, 3, and 4. range(5) produces five numbers, starting at 0 and stopping before 5.

range() accepts up to three arguments:

CallProduces
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 10, 2)0, 2, 4, 6, 8
range(5, 0, -1)5, 4, 3, 2, 1

The stop value is never included. To count from 1 to 10, write range(1, 11).

If you do not need the number itself, name the variable with an underscore: for _ in range(3):. It tells readers the value is not used.

Loop over a string

A string is a sequence of characters, so a for loop visits one character at a time:

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

Get the index too with enumerate()

When you need the position as well as the item, use enumerate():

pythonpython
tasks = ["write", "test", "deploy"]
 
for index, task in enumerate(tasks, start=1):
    print(index, task)
texttext
1 write
2 test
3 deploy

enumerate() yields pairs of a counter and an item. Without start=1 the counter begins at 0.

Avoid for i in range(len(tasks)): followed by tasks[i]. It works, but enumerate() is shorter and harder to get wrong.

Loop over a dictionary

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

pythonpython
prices = {"tea": 2.5, "coffee": 3.0, "juice": 4.0}
 
for item, price in prices.items():
    print(f"{item}: {price:.2f}")
texttext
tea: 2.50
coffee: 3.00
juice: 4.00

Use .values() when you only need the values. More patterns are in iterating through Python collections.

Loop over two lists together with zip()

zip() pairs up items from two or more sequences:

pythonpython
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 79]
 
for name, score in zip(names, scores):
    print(name, score)

zip() stops at the end of the shortest sequence, so no error is raised if the lists differ in length.

Build a result inside a loop

A very common pattern is to start with an empty or zero value and update it on every pass:

pythonpython
prices = [19.99, 5.49, 3.50]
total = 0
 
for price in prices:
    total += price
 
print(round(total, 2))  # 28.98

The same idea builds a new list:

pythonpython
names = ["ada", "grace", "linus"]
capitalized = []
 
for name in names:
    capitalized.append(name.capitalize())
 
print(capitalized)  # ['Ada', 'Grace', 'Linus']

When the loop only builds a list like this, a list comprehension does the same job in one line: [name.capitalize() for name in names].

Stop early or skip an item

break ends the loop at once. continue skips to the next item.

pythonpython
for number in [3, 8, -2, 7]:
    if number < 0:
        print("Negative number found, stopping.")
        break
    print(number)

This prints 3 and 8, then the message. The 7 is never reached.

The else clause on a loop

A for loop can have an else block. It runs only when the loop finishes without hitting break:

pythonpython
primes = [2, 3, 5, 7]
 
for n in primes:
    if n % 2 == 0 and n > 2:
        print("Found an even number above 2.")
        break
else:
    print("No even number above 2.")

This prints No even number above 2. The feature is handy for searches, where else means "not found". Many programs never need it.

Common mistakes

MistakeWhat happensFix
for i in 5:TypeError: 'int' object is not iterableUse range(5)
Expecting range(1, 10) to include 10The loop stops at 9Use range(1, 11)
Removing items from the list you are looping overItems get skippedLoop over a copy, or build a new list
Forgetting the colonSyntaxErrorEnd the for line with :
Reassigning the loop variable to change the listThe list is unchangedAssign by index, or build a new list

Here is the removal problem and its fix:

pythonpython
numbers = [1, 2, 2, 3]
 
# Build a new list instead of removing while looping
numbers = [n for n in numbers if n != 2]
print(numbers)  # [1, 3]

for or while?

Use a for loop when you are going through a collection or repeating a known number of times. Use a while loop when you repeat until a condition changes and cannot know the number of passes in advance. The overview in Python control flow compares the two side by side.

Rune AI

Rune AI

Key Insights

  • A for loop runs its block once for every item in a list, string, dictionary, range, or other iterable.
  • range(stop) counts from 0 up to, but not including, stop; range(start, stop, step) gives full control.
  • Use enumerate() when you need the index and the item together.
  • Use .items() to loop over the keys and values of a dictionary, and zip() to loop over two lists in step.
  • break leaves the loop early and continue skips to the next item.
  • Do not add or remove items from a list while looping over it; build a new list instead.
RunePowered by Rune AI

Frequently Asked Questions

How do I write a for loop in Python?

Write for, a variable name, in, the sequence to loop over, and a colon. Then indent the block to repeat. For example, for fruit in fruits: followed by an indented print(fruit) prints every item in the list.

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

Loop over range(). for i in range(5) runs five times with i going from 0 to 4. Use range(1, 6) to count from 1 to 5, because the stop value is not included.

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

Use enumerate(). for index, item in enumerate(items) gives the position and the item on each pass. Add start=1 to begin counting from 1 instead of 0.

How do I loop through a dictionary in Python?

Looping over the dictionary itself gives the keys. Use for key, value in my_dict.items() to get both, or my_dict.values() for the values only.

Can I change a list while looping over it?

Changing item values by index is fine, but adding or removing items while looping makes Python skip or repeat items. Loop over a copy with for item in items[:] or build a new list instead.

Conclusion

The for loop is the tool you will use most for repetition in Python. Loop directly over the items you care about, reach for range() when you need numbers, enumerate() when you need positions, and zip() when you need two sequences at once.