Academic Block

Python for Loops & range()Get Certified

What Is a for Loop?

A loop repeats a block of code. Instead of writing the same instruction ten times, you write it once and let Python run it ten times. A for loop is the loop you use when you want to go through the items of a collection one at a time, or to repeat something a known number of times. Python’s for loop is different from the counting loop of languages such as C or Java: it does not count with a variable that you update yourself. It takes an iterable, such as a list, a string, or a range(), and hands you its items one by one.

  • Syntax: for item in iterable: followed by an indented block.
  • Iterables: lists, tuples, strings, dictionaries, sets, and range() can all be looped over.
  • range(): produces a sequence of numbers to repeat an action a fixed number of times.
  • Helpers: enumerate(), zip(), reversed(), and sorted() make loops shorter and clearer.
  • Control: break stops a loop, continue skips to the next item, and else runs when the loop was not stopped.
  • Nested loops: a loop inside a loop works through rows and columns.

Looping Over a List

The basic form is for variable in collection:. On each repetition Python assigns the next item to the loop variable and runs the indented block once. When the items are used up, the loop ends and the program continues with the first line that is not indented. You can choose any name for the loop variable, and a good name describes one item, such as fruit for a list called fruits.

Try It: Your First for Loop

Click Test My Code. Then add a fourth fruit to the list and run it again.

What this code does: It creates a list of three fruits and prints each one on its own line with a for loop. The last line is not indented, so it runs once after the loop has finished.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
print("Done")

Looping Over Strings, Tuples, and Dictionaries

Anything that is iterable can follow the word in. A string gives its characters one by one, and a tuple or set gives its items like a list. A dictionary gives its keys by default. To get the values use .values(), and to get keys and values together use .items(), which produces pairs that you can unpack into two loop variables.

Try It: Strings and Dictionaries

Click Test My Code. Notice how the two dictionary loops give the same information in two different ways.

What this code does: It prints the three characters of a string. It then loops over a dictionary of prices twice: once over the keys and looking up each value by hand, and once over the key and value pairs returned by items().
for letter in "Hi!":
    print(letter)
prices = {"tea": 3, "coffee": 5}
for item in prices:
    print(item, prices[item])
for item, price in prices.items():
    print(f"{item} costs {price}")

The range() Function

To repeat something a number of times, or to work with numbers, use range(). It produces a sequence of integers and comes in three forms:

  • range(stop) counts from 0 up to, but not including, stop. So range(5) gives 0, 1, 2, 3, 4.
  • range(start, stop) begins at start, as in range(2, 8).
  • range(start, stop, step) moves by step. A negative step counts down.

A range does not store all its numbers. It calculates each one when needed, so range(1000000) uses almost no memory. Use list() to see the numbers it would produce. The arguments must be integers. For decimal steps, calculate the values inside the loop.

Try It: What range() Produces

Click Test My Code. Predict each line before you look at the output, especially the one that counts down.

What this code does: It converts four different ranges into lists so that you can see their numbers. The last line shows that a range knows its length and can test whether it contains a number.
print(list(range(5)))
print(list(range(2, 8)))
print(list(range(0, 20, 5)))
print(list(range(10, 0, -3)))
print(len(range(100)), 3 in range(5))

Counting and Accumulating

A very common pattern is to create a variable before the loop and update it inside the loop. This is called an accumulator. Use a number to build a total or a count, a list to collect results, or a string to build text. If you do not need the loop variable, the convention is to name it _, as in for _ in range(3):. The loop variable also stays available after the loop and keeps the value of the last item.

Try It: A Running Total

Click Test My Code. Change range(1, 6) to range(1, 11) and predict the final sum before you run it.

What this code does: It starts a total at zero and adds the numbers 1 to 5 to it, one per repetition. Inside the loop it prints the value of i and the running total. After the loop it prints the final sum.
total = 0
for i in range(1, 6):
    total += i
    print(f"i = {i}, total = {total}")
print("Sum:", total)

enumerate(), zip(), and reversed()

Python provides several built-in helper functions that make working with loops easier, faster, and more efficient. Functions like range(), enumerate(), and zip() help you iterate over sequences, access index values, and process multiple collections without manually managing counters. These tools make your code cleaner, shorter, and less prone to errors.

  • enumerate(items, start=0) gives pairs of a counter and an item. It replaces range(len(items)) when you need the position.
  • zip(a, b) walks through two or more collections side by side and stops at the shortest one.
  • reversed(items) goes through a sequence from the end to the start.
  • sorted(items) returns a new sorted list, so you can loop in order without changing the original.

Try It: Positions, Pairs, and Reverse Order

Click Test My Code. Add a fourth name without adding a fourth score and see where zip() stops.

What this code does: It numbers a list of names starting at 1 with enumerate(), pairs each name with a score using zip(), and counts down from 2 to 0 with reversed(). The end=" " argument keeps the countdown on one line.
names = ["Asha", "Ben", "Chen"]
scores = [90, 72, 85]
for index, name in enumerate(names, start=1):
    print(index, name)
for name, score in zip(names, scores):
    print(f"{name}: {score}")
for i in reversed(range(3)):
    print(i, end=" ")
print()

break, continue, and else

Two keywords change the normal flow of a loop. break leaves the loop at once, and the program continues after the loop. continue skips the rest of the current repetition and jumps to the next item. A for loop can also have an else block. It runs when the loop reaches the end of its items without being stopped by break. This is useful for searching: the else block is the “not found” case.

Try It: Skipping and Stopping

Click Test My Code. Then change 20 to 4, so that no even number is above 10, and watch the else block run.

What this code does: It looks through a list for the first even number above 10. Odd numbers are skipped with continue. Small even numbers are printed. When a number matches, the loop prints it and stops with break, so the else block is skipped.
numbers = [3, 8, 12, 5, 20]
for n in numbers:
    if n % 2 != 0:
        continue
    if n > 10:
        print("First even number above 10:", n)
        break
    print("Even:", n)
else:
    print("No even number above 10")

Nested Loops

A loop can contain another loop. For every repetition of the outer loop, the inner loop runs completely from start to finish. Nested loops are the natural way to work with rows and columns, such as tables, grids, and combinations. A loop that repeats 3 times with an inner loop that repeats 3 times runs the inner block 9 times in total. Each level of nesting adds another level of indentation.

Try It: A Multiplication Grid

Click Test My Code. Change both range(1, 4) to range(1, 6) to make a larger grid.

What this code does: The outer loop goes through three rows and the inner loop goes through three columns. Each cell holds the product of the row and the column number. The cells are printed on one line with a width of 3 characters, and an empty print() starts a new row.
for row in range(1, 4):
    for col in range(1, 4):
        print(f"{row * col:3}", end="")
    print()

Building Lists with Loops

A for loop is the usual way to build a new list: start with an empty list and use append() inside the loop. A list comprehension is a shorter form of the same idea that you will meet in a later lesson. Loops are also how you count matches, for example how often a letter appears in a word.

Try It: Squares, Evens, and Counting

Click Test My Code. Change the letter that is counted from "l" to "e".

What this code does: It builds a list of the squares of 1 to 5 with a loop and append(). It then builds a list of even numbers with a list comprehension, and finally counts how many times the letter l appears in a word.
squares = []
for n in range(1, 6):
    squares.append(n ** 2)
print(squares)
evens = [n for n in range(10) if n % 2 == 0]
print(evens)
word = "level"
count = 0
for ch in word:
    if ch == "l":
        count += 1
print(count)

Using for Loops with User Input

Loops let a program process any amount of data. A common way to read several values at once is to ask for one line, split it into words, and loop over the words. Remember that every word is still text, so convert it with int() or float() before calculating.

Try It: A Multiplication Table

The Program Input box is already filled with 7. Click Run Code straight away, then try another number such as 12.

What this code does: It reads a whole number and uses a for loop with range(1, 11) to print the multiplication table of that number from 1 to 10.
n = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{n} x {i} = {n * i}")

Try It: Sum, Average, and Largest

The Program Input box is filled with 4 8 15 16 23 42. Click Run Code, then enter your own numbers separated by spaces.

What this code does: It reads a line of numbers and splits it into words. A loop converts each word to a float, adds it to a total, and keeps track of the largest value seen so far. After the loop it prints the count, the sum, the average, and the largest number.
numbers = input("Enter numbers separated by spaces: ").split()
total = 0
largest = None
for text in numbers:
    value = float(text)
    total += value
    if largest is None or value > largest:
        largest = value
print(f"Count: {len(numbers)}")
print(f"Sum: {total}")
print(f"Average: {total / len(numbers):.2f}")
print(f"Largest: {largest}")
Tip: Loop over the items directly. Write for fruit in fruits: instead of for i in range(len(fruits)): followed by fruits[i]. When you need the position as well, use enumerate().

Common Mistakes with for Loops

  • Forgetting that the stop value is excluded: range(5) gives 0 to 4, not 1 to 5. Use range(1, 6) to count from 1 to 5.
  • Forgetting the colon or the indentation: the for line must end with :, and the body must be indented, otherwise Python raises a SyntaxError or an IndentationError.
  • Looping over a number: for i in 5: raises a TypeError, because an integer is not iterable. Use range(5).
  • Changing a list while looping over it: adding or removing items of the list you are looping over gives confusing results. Loop over a copy, such as for x in items[:]:, or build a new list.
  • Resetting the accumulator inside the loop: writing total = 0 inside the loop erases the total on every repetition. Create it before the loop.
  • Using floats in range(): range(0, 1, 0.1) raises a TypeError. Loop over integers and divide, as in i / 10.
  • Using range(len(items)) without a need: it is longer and easier to get wrong than looping over the items, or using enumerate().
  • Misreading for-else: the else block runs when the loop was not stopped by break, not when the loop is empty or when a condition is false.

Key Takeaways

  • A for loop goes through the items of any iterable and runs its indented block once per item.
  • range(stop), range(start, stop), and range(start, stop, step) produce integers, and the stop value is never included.
  • Strings give characters, dictionaries give keys by default, and items() gives key and value pairs.
  • Create accumulators such as totals, counts, and result lists before the loop and update them inside it.
  • enumerate(), zip(), reversed(), and sorted() make loops shorter and clearer.
  • break stops the loop, continue skips to the next item, and else runs when the loop finishes without a break.
  • In nested loops, the inner loop runs completely for every repetition of the outer loop.

Frequently Asked Questions

What is a for loop in Python?

A for loop repeats a block of code once for each item of an iterable such as a list, a string, a dictionary, or a range. It is written as for item in iterable: followed by an indented block. On each repetition the next item is stored in the loop variable.

How does the range() function work in Python?

The range() function produces a sequence of integers. range(5) gives 0 to 4, range(2, 8) gives 2 to 7, and range(0, 20, 5) gives 0, 5, 10, 15. The stop value is never included, and a negative step counts down.

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

Use enumerate(), for example for i, item in enumerate(items):. It gives the position and the item together. Add start=1 to begin counting at 1 instead of 0.

How do I loop through a dictionary in Python?

A plain for loop over a dictionary gives its keys. Use .values() to loop over the values, and .items() to loop over key and value pairs, for example for key, value in data.items():.

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

A for loop goes through a known collection or a known number of repetitions. A while loop repeats as long as a condition is true, which makes it better when you do not know in advance how many repetitions are needed.

What does else do in a Python for loop?

The else block of a for loop runs when the loop reaches the end of its items without being stopped by break. If the loop is stopped by break, the else block is skipped. It is often used for the “not found” case of a search.

How do I loop backwards in Python?

Use reversed(), as in for item in reversed(items):, or use a range with a negative step, such as range(10, 0, -1). Reversed does not change the original list.

How do I stop or skip an iteration of a for loop?

Use break to leave the loop completely, and continue to skip the rest of the current repetition and go on with the next item. Both are usually placed inside an if statement.

Ready for the next step?Learn how to repeat code for as long as a condition is true.
Next: while Loops →