Python online course

Python for Loops: Iterating Over Sequences

Learn how Python for loops repeat a block of code for each item in a string, list, or range, including syntax, execution flow, and common mistakes.

What Is a Loop?

A loop is a programming structure used to repeat work. Loops automate tasks that would otherwise require writing similar statements many times.

A for loop runs a block of code once for each item in an iterable. An iterable is a value that can provide items one at a time, such as a string, list, tuple, dictionary, or range.

Each pass through the loop is called an iteration. During one iteration, Python obtains the next item, assigns it to a loop variable, and runs the loop body.

Before continuing, review Python strings, variables, assignment, and print().

Basic Python for Loop Syntax

for item in iterable:
    # loop body
    statement

This structure contains a for keyword, a loop variable, the in keyword, an iterable expression, and a colon. The colon begins the code block. Indentation tells Python which statements belong to the loop body.

The indented body runs once for every item supplied by the iterable. Python automatically updates the loop variable before each iteration.

PartRoleExample
forStarts the loop statementfor
Loop variableStores the item currently being processedletter
inSeparates the variable from the iterablein
IterableSupplies items to process"Hello World!"
Loop bodyRuns for every itemprint(letter)

Choose a meaningful singular name for the loop variable. Names such as letter, number, and name make it clear what the current item represents.

Iterating Through a String

A string is a sequence of characters, so it is iterable. A for loop processes a string one character at a time.

for letter in "Hello World!":
    print(letter)

Output:

H
e
l
l
o
 
W
o
r
l
d
!

Because print(letter) is indented, it runs during every iteration. The space between Hello and World! is also a character, so it produces an empty-looking line in the displayed output.

Following the Execution Flow

  1. Python takes the first character, H, and assigns it to letter.
  2. Python runs the indented statement, so H is printed.
  3. Python takes the next character, e, assigns it to letter, and prints it.
  4. Python continues with each remaining character. The value of letter changes automatically on every iteration.
  5. After the final character has been processed, the loop ends naturally.
IterationCurrent value of letterOutput
1HH
2ee
3ll

Using range() with a for Loop

range() is a built-in function commonly used when an operation must be repeated a known number of times. It produces integer values that a for loop can process.

The range(stop) Form

With one argument, range(stop) starts at zero and stops before the supplied value. Therefore, range(5) produces 0, 1, 2, 3, and 4—not 5.

for number in range(5):
    print(number)

Output:

0
1
2
3
4

The loop body runs five times because range(5) supplies five values.

Repeating a Message

for number in range(3):
    print("Welcome")

This prints Welcome three times. The loop variable receives 0, 1, and 2, although the example does not use the variable inside the body.

For a starting value and a step size, use additional arguments such as range(1, 4) for 1 through 3, or range(0, 10, 2) for even values from 0 through 8. The stop value remains excluded. See using a for loop with the range function for more range patterns.

Where the Loop Body Ends

Indentation determines whether a statement belongs to the loop. Every statement with the loop body's indentation runs once per item.

for letter in "Hi":
    print("Inside:", letter)

print("Done")

The first print() runs twice, once for each character. The second print() is not indented, so it runs once after the loop finishes.

If a statement should process every item, keep it inside the loop. If it should run only after all items have been processed, place it outside the loop.

Common Syntax and Logic Mistakes

Missing the Colon

A colon is required after the iterable expression in the for header.

for letter in "Hi"
    print(letter)

This causes a SyntaxError. Correct it by adding the colon:

for letter in "Hi":
    print(letter)

For more information about Python syntax problems, see syntax and logical errors.

Failing to Indent the Body

for letter in "Hi":
print(letter)

The statement that should repeat must be indented:

for letter in "Hi":
    print(letter)

Incorrect indentation can produce an IndentationError or place a statement outside the loop unintentionally. Use consistent indentation, conventionally four spaces.

Expecting range(n) to Include n

for number in range(3):
    print(number)

This prints 0, 1, and 2. If you need 1, 2, and 3, use:

for number in range(1, 4):
    print(number)

Putting Output Outside the Loop

for letter in "Hi":
    current = letter
print(current)

Here, print(current) runs once, after the loop, so only the final value is displayed. To print every value, move the statement into the loop:

for letter in "Hi":
    current = letter
    print(current)

Using an Unclear Loop Variable

A name such as x may hide what each item represents. Prefer a descriptive singular name:

for name in names:
    print(name)

Clear names make loops easier to read and debug. See Python variable names for naming guidance.

What You Should Remember

  • A for loop repeats a block of code for each item in an iterable.
  • An iteration is one pass through the loop body.
  • The loop variable receives the current item and changes automatically on the next iteration.
  • Strings are iterables, so a string can be processed character by character.
  • The colon starts the loop block, and indentation defines the loop body.
  • range(stop) starts at zero and excludes the stop value.
  • Statements inside the loop run repeatedly; statements outside it run according to the surrounding program flow.

Next, explore Python lists and while loops. Lists provide collections of values to iterate over, while while loops repeat based on a condition.