Python Basics

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.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • Looping over lists and strings
  • Counting with range()
  • Getting the position with enumerate(), plus break and continue
for i, lang in enumerate(langs, start=1)
  1. 11, "Python"first round
  2. 22, "JavaScript"second round
  3. 33, "Go"last item: the loop ends
↺ Python takes the next item automatically

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.

From a roll call to code
languages📋 The class list
for position, language in enumerate(languages, start=1):🧑‍🏫 Go down the list, counting from 1
print(f"{position}. {language}")📣 Do the same thing for each student
end of the list🏁 The loop stops by itself
One round per item, in order, until the list runs out.
In one sentence

A 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

  1. for position, language in enumerate(languages, start=1): runs the block once for each item in languages.
  2. enumerate gives two values per round: a counter and the item, so you do not keep a counter yourself.
  3. start=1 makes the counter begin at 1 instead of 0, which reads better for people.
  4. 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 while loop.
  • 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

Run code →
main.py
languages = ["Python", "JavaScript", "Go"]

for position, language in enumerate(languages, start=1):
    print(f"{position}. {language}")
Get a Run button for this example

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.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in the Python compiler →

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, continueStop 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.

Problem
for i in range(1, 5):
    print(i)  # 1, 2, 3, 4
Fix
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.

Problem
names = ["Ada", "Lin"]
for i in range(len(names)):
    print(i, names[i])
Fix
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.

Problem
nums = [1, 2, 3]
for n in nums:
    n = n * 2
print(nums)  # [1, 2, 3]
Fix
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.

Problem
for n in [1, 2, 3]
print(n)
Fix
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.

All challenges