How to Use a For Loop in Python

A Python for loop runs a block of code once for each item in a sequence or other iterable. Use it to process items, repeat an action a known number of times, or build a result without writing the same code over and over.

You need Python and a place to run a short script, such as a local interpreter or a code editor. The examples use basic Python syntax; no extra packages are required. Indentation matters: the statements inside a loop must be indented consistently beneath the for line.

What You’ll Need

  • A working Python installation or an online Python environment you trust.
  • A text editor, notebook, or interactive prompt where you can run Python code.
  • A basic understanding of variables, strings, and lists. You can still follow along if these are new; each example shows how they are used.

Step-by-Step

  1. Choose what the loop will go through. A for loop takes items from an iterable, which is an object Python can provide one item at a time. Common examples include a list, a string, a tuple, a dictionary, and a range. Start with a list:
    colors = ["blue", "green", "red"]

    The list holds three values. The loop can visit each value in order.

  2. Write the loop header. Add for, a variable name for the current item, in, and the iterable, followed by a colon:
    for color in colors:

    Here, color is assigned the next value from colors each time the loop runs. The name is your choice; use one that makes the current item clear. Python does not require the loop variable to match the list name.

  3. Indent the code that should repeat. Put the loop body on the next line and indent it, commonly by four spaces:
    for color in colors:
        print(color)

    Run the code. It prints each color on its own line. The indented statement runs once for each item; the loop ends when there are no more items. Keep all statements in the same loop body aligned at the same indentation level.

  4. Try the loop with a string. A string is also iterable. Python visits its characters in order:
    for letter in "cat":
        print(letter)

    This prints one character per line. The same pattern works with other iterable values, though the item produced depends on the type. For example, iterating over a list gives its elements, while iterating over a string gives its characters.

  5. Repeat code a set number of times with range(). Use range() when you need a series of integers rather than a pre-existing collection:
    for number in range(5):
        print(number)

    This prints 0 through 4. The ending value is excluded, so range(5) produces five values starting at zero. To start somewhere other than zero, provide a start and stop value:

    for number in range(2, 6):
        print(number)

    This prints 2, 3, 4, and 5. The stop value, 6, is not included.

  6. Use the current item in a calculation. The loop variable is available inside the indented body, so you can calculate with it or format it into a message:
    prices = [4, 7, 3]
    for price in prices:
        total_with_fee = price + 1
        print(total_with_fee)

    Each pass assigns one list value to price, calculates a new value, and prints it. If you need to keep a running total, initialize it before the loop and update it in the body:

    scores = [6, 8, 5]
    total = 0
    for score in scores:
        total = total + score
    print(total)

    The final print is not indented, so it runs after the loop has finished.

  7. Build a new list when you want to keep results. Printing is useful for checking output, but it does not save the results for later. Start with an empty list and append each result:
    numbers = [1, 2, 3]
    doubled = []
    for number in numbers:
        doubled.append(number * 2)
    print(doubled)

    The result is [2, 4, 6]. Initialize the output list before the loop, then append inside it. If you only need a transformed list, a list comprehension is another option, but a regular loop is often easier to read while learning or when several steps are involved.

  8. Get both an index and an item when needed. If a task needs each item’s position as well as its value, use enumerate():
    tasks = ["read", "write", "review"]
    for index, task in enumerate(tasks):
        print(index, task)

    By default, the index begins at zero. To count from a different starting value, pass start, for example enumerate(tasks, start=1). Prefer this approach to manually increasing a separate counter when you need positions.

  9. Check the boundary and run a small test. Before relying on a loop, confirm what items it will produce and whether the body should run for every item. Try a short list or a small range, inspect the output, and then use the intended data. For a loop that calculates a total or creates a list, print the final result after the loop to confirm it is what you expect.

Common Mistakes

  • Forgetting the colon: A loop header must end with :. Without it, Python reports a syntax error.
  • Incorrect indentation: The loop body must be indented. If a line meant to repeat is aligned with for, it runs after the loop instead; inconsistent indentation can also cause an error.
  • Expecting range() to include its stop value: The stop is excluded. To print through 5, use range(6) or give an appropriate start and stop.
  • Using the wrong variable: Inside the loop, use the loop variable, such as color, rather than the whole list when you mean the current item.
  • Overwriting an accumulated result: If you set total = score on every pass, the variable keeps only the latest score. Update it with total += score instead.
  • Changing a list while iterating over it: Removing or inserting items in the same list being traversed can cause items to be skipped or processed unexpectedly. If you need to filter, build a separate result list or iterate over a copy.

Tips

  • Use a descriptive singular loop variable, such as student for items in students. Clear names make the body easier to understand.
  • Keep each loop body focused. If a block becomes long, move a meaningful task into a function and call it from the loop.
  • Use break to leave a loop early when a condition is met, and continue to skip the rest of the current pass and move to the next item. Use these sparingly so the loop remains easy to follow.
  • Use a nested loop only when you really need to process combinations, such as every row and column in a grid. The inner loop runs for each pass of the outer loop, so nested loops can do more work than a single loop.
  • When iterating through a dictionary, a plain loop gives its keys. Use dictionary.items() when you need both keys and values:
    for key, value in settings.items():
        print(key, value)

Troubleshooting

You see an indentation or syntax error. Check that the header ends with a colon, then make sure the body is indented consistently. In many editors, spaces and tabs can be mixed accidentally; convert the block to spaces or use the editor’s indentation controls.

The loop runs zero times. Check whether the iterable is empty or whether the range’s start and stop values produce any numbers. For example, range(4, 2) is empty with the default step because it counts upward from a value already beyond the stop.

The output is off by one. Review the exclusive stop rule for range(). Write down the first and last values you intend to process, then choose a stop value one beyond the last value when counting upward by one.

The result is missing or incorrect. Confirm that you initialized any total or output list before the loop, updated it inside the loop, and placed the final print or return at the intended indentation. Add a temporary print of the loop variable to see what values are actually being processed.

You get a “not iterable” error. The value after in must be iterable. Check that a variable contains a list, string, range, or another iterable rather than a single number. If you want to repeat a fixed number of times, use range().

Frequently Asked Questions

What does a for loop do in Python?
It takes items from an iterable one at a time and runs an indented block for each item. It is commonly used to process collections or repeat an action across a range of values.

How is a for loop different from a while loop?
A for loop is a natural fit when you have an iterable to visit. A while loop repeats as long as a condition remains true, so you must ensure that the condition eventually changes if the loop should stop.

Does range(5) include the number five?
No. It starts at zero by default and stops before five, producing the values zero through four.

Can I use break or continue in a for loop?
Yes. break ends the loop immediately; continue skips the remaining statements in the current pass and proceeds to the next item.

How do I loop through a dictionary’s keys and values?
Use for key, value in dictionary.items():. A loop over the dictionary alone visits its keys, while .items() supplies key-value pairs.

Can a for loop go through a list more than once?
Yes. A list can be iterated over again in a later loop. However, an iterator that has already been consumed may need to be recreated before it can produce its items again.