Python For Loop: range(), enumerate() and Examples
Repeat an action for every item in a list, every letter in a word or every number in a range.
- Looping over lists and strings
- Counting with range()
- Getting the position with enumerate(), plus break and continue
- 1
1, "Python"first round - 2
2, "JavaScript"second round - 3
3, "Go"last item: the loop ends
One round per item
The problem
Often you need to do the same thing for every item in a collection: print every name, add up every price, check every file. Writing one line per item is impossible when the list has 1,000 items or when you do not know how long it will be.
Think of it like this
A for loop is like a teacher calling the roll. The teacher goes down the class list one name at a time and does the same thing for each student, then stops at the end of the list. enumerate is the teacher also saying each student's number.
languages📋 The class listfor position, language in enumerate(languages, start=1):🧑🏫 Go down the list, counting from 1print(f"{position}. {language}")📣 Do the same thing for each studentend of the list🏁 The loop stops by itselfA for loop takes the items of a collection (a list, a string, a range) one by one and runs the same block of code for each of them.
Key points
for position, language in enumerate(languages, start=1):runs the block once for each item inlanguages.enumerategives two values per round: a counter and the item, so you do not keep a counter yourself.start=1makes the counter begin at 1 instead of 0, which reads better for people.- The loop ends by itself after the last item; you never write a stop condition.
When should you use it?
- Processing every item in a list, every character in a string or every line in a file.
- Repeating something a known number of times with
range, such as 10 rounds of a game. - Building a total, a count or a new list from existing data.
When not to use it
- You do not know how many rounds are needed, such as asking until the answer is valid: use a
whileloop. - You only need a new list from a simple rule: a list comprehension is shorter.
See how it works
Press Step to run the loop one move at a time. Watch the condition being checked, the body running and the trace table growing row by row.
Example code
languages = ["Python", "JavaScript", "Go"]
for position, language in enumerate(languages, start=1):
print(f"{position}. {language}")
Result of running the code
1. Python
2. JavaScript
3. Go
Code explanation
Enumerate supplies both a zero-based index and the current item. The start argument changes the displayed position to begin at 1.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Python for loop patterns
for item in items: | Run the block once for each item |
for i in range(5): | Count from 0 to 4 |
for i in range(2, 10, 2): | Count 2, 4, 6, 8 (start, stop, step) |
for i, item in enumerate(items): | Get the index and the item together |
for a, b in zip(xs, ys): | Loop over two lists side by side |
for key, value in d.items(): | Loop over a dictionary's keys and values |
for ch in "hello": | Loop over the characters of a string |
for item in reversed(items): | Loop backwards |
break, continue | Stop the loop, or skip to the next item |
for ... else: | The else block runs when the loop ends without break |
[x * 2 for x in nums] | Build a new list in one line (list comprehension) |
Common mistakes with Python for loops
Off by one with range()
range(start, stop) stops before stop. To include 5, the stop value must be 6.
for i in range(1, 5):
print(i) # 1, 2, 3, 4
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
Using range(len(...)) when you only need the items
Loop over the items directly, and use enumerate() when you also need the index.
names = ["Ada", "Lin"]
for i in range(len(names)):
print(i, names[i])
names = ["Ada", "Lin"]
for i, name in enumerate(names):
print(i, name)
Changing the loop variable to change the list
The loop variable is a new name for each item, so reassigning it does not change the list.
nums = [1, 2, 3]
for n in nums:
n = n * 2
print(nums) # [1, 2, 3]
nums = [1, 2, 3]
nums = [n * 2 for n in nums]
print(nums) # [2, 4, 6]
Forgetting the colon or the indentation
The for line must end with a colon and the body must be indented, or Python raises SyntaxError or IndentationError.
for n in [1, 2, 3]
print(n)
for n in [1, 2, 3]:
print(n)
Frequently asked questions
How do I get the index in a Python for loop?
Use enumerate(): for i, item in enumerate(items). It gives the index and the item together, starting at 0, or at another number with enumerate(items, start=1).
How do I loop backwards in Python?
Use reversed(items) for a list, or range(start, stop, -1) for numbers, for example range(10, 0, -1) counts from 10 down to 1.
What is the difference between a for loop and a while loop?
A for loop runs once for each item in a sequence, so it ends by itself. A while loop runs as long as a condition is true, which suits cases where you do not know the number of steps in advance.
How do I stop a for loop early?
Use break to leave the loop immediately, or continue to skip the rest of the current step and move on to the next item.
How do I loop over two lists at the same time?
Use zip(): for name, score in zip(names, scores). It stops at the end of the shorter list.
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Sum of Odd Numbers Add every odd number up to a limit. Easy
- Multiplication Table Row List the first multiples of a number. Easy
- Factorial Multiply all positive integers up to n. Easy