VMware ESXi and vSphere Cluster Management

Python for Loops: Iterating Over Sequences

Learn Python for loops, iteration variables, strings, range(), loop bodies, ranges, common mistakes, and practical examples.

A for loop repeats a block of code once for each item supplied by an iterable. Instead of writing the same statement many times, you write the statement once and let Python repeat it.

For example, a program can inspect every character in a string, greet every name in a list, or perform an action a known number of times. One complete pass through the loop body is called an iteration.

What a for loop does

A for loop is a control-flow statement that processes items one at a time. An iterable is an object that can provide items one at a time to a loop. Common iterables include strings, lists, tuples, dictionaries, sets, ranges, and files.

A sequence is an ordered collection of items. Strings, lists, tuples, and ranges are common sequences. We will begin with strings because a string can be viewed as a sequence of characters.

The execution order is:

  1. Python obtains the next item from the iterable.
  2. It assigns that item to the loop variable.
  3. It executes every statement in the indented loop body.
  4. It continues with the next item.
  5. The loop ends when no items remain.

If the iterable is empty, the body runs zero times.

Basic for loop syntax

for item in iterable:
    statement
Syntax partPurposeExample
for keywordStarts a for-loop statement.for
Loop variableReceives the current item during each iteration.letter
in keywordConnects the loop variable to the source of values.letter in
IterableSupplies items one at a time."Hello"
ColonMarks the beginning of the loop body.:
Indented loop bodyContains statements executed for every item.print(letter)

Python uses indentation, or leading whitespace, to group statements into blocks. Every statement that should run for each item must be indented consistently beneath the loop header.

for letter in "Hello":
    print(letter)

Here, for starts the loop, letter is the loop variable, "Hello" is the iterable, and print(letter) is the loop body.

The loop variable

The loop variable is the name that receives the current item on each pass. Its value changes automatically as iteration advances. Choose a name that describes the item, such as letter, number, name, or score.

for name in ["Ava", "Noah", "Mia"]:
    print("Hello, " + name)

On the first iteration, name is "Ava"; on the second, it is "Noah"; and on the third, it is "Mia". After the loop finishes, the variable normally remains available and contains the last processed value, "Mia". If you need all values later, store them in another collection rather than relying on the loop variable.

Iterating over a string

Strings are sequences of characters, so a for loop visits each character from left to right.

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

The body runs once for every character. The first iteration processes H, middle iterations process the remaining letters and the space, and the final iteration processes !. The print statement therefore produces one output action per character.

Spaces and punctuation are characters too. They are not skipped automatically. In the example, the space between World and ! causes an iteration that prints a blank line.

Iteration numberCurrent characterValue stored in the loop variableOutput
1H"H"H
2i"i"i
3space" "blank line
4!"!"!

The loop variable is the current character, not the entire string. The string remains the iterable that supplies the characters.

Using range() with for loops

range() is a built-in function that creates an iterable progression of integers. It is useful when you want to repeat an action a known number of times or process a sequence of numbers.

ExpressionValues producedTypical use
range(5)0, 1, 2, 3, 4Repeat five times.
range(2, 6)2, 3, 4, 5Start at 2 and count upward.
range(2, 10, 2)2, 4, 6, 8Count upward by 2.
range(10, 0, -2)10, 8, 6, 4, 2Count backward by 2.

range(stop)

With one argument, range(stop) starts at zero and stops before the supplied value.

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

This prints 0 through 4, not 5. When the generated number is intentionally unused, use the conventional throwaway variable _:

for _ in range(5):
    print("Practice makes progress")

range(start, stop)

With two arguments, the first is start and the second is stop. The start value is included, but the stop value is excluded.

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

This prints the values 1, 2, 3, 4, and 5. To include an apparent endpoint such as 5, use 6 as the stop value.

range(start, stop, step)

The optional step specifies how much the value changes between iterations. A positive step counts upward; a negative step counts downward.

for number in range(10, 0, -2):
    print(number)

This prints 10, 8, 6, 4, and 2. A descending range needs a negative step and a stop value below the start. A range whose direction and step do not agree produces no values.

Multiple statements in a loop body

A loop body can contain several equally indented statements. Every one of them runs for each item.

scores = [8, 10, 7]
total = 0

for score in scores:
    print("Processing:", score)
    total = total + score

print(total)

total is an accumulator: a variable that keeps a running result. The loop adds each score to it. Statements with less indentation, such as the final print(total), run after the loop rather than once per score.

Readable loop design

  • Use descriptive names such as letter, name, and score when they clarify the data.
  • Use _ when a generated value is deliberately unused.
  • Avoid reusing names in ways that hide which data is being processed.
  • Keep the loop body focused on the work performed for one item.
  • Indent all statements in the same block consistently, typically with four spaces.

Common beginner mistakes

Missing the colon

# Incorrect
for letter in "Hi"
    print(letter)

# Correct
for letter in "Hi":
    print(letter)

The colon must end the loop header before the indented body begins.

Incorrect or inconsistent indentation

for number in range(3):
    print(number)
    print("inside the loop")

Both statements are equally indented, so both belong to the loop. Inconsistent indentation can cause an IndentationError or change which statements execute inside the loop.

Expecting range() to include stop

range(1, 5) produces 1 through 4. For values 1 through 5, use range(1, 6).

Using a non-iterable after in

# TypeError: an integer is not iterable in this context
for number in 5:
    print(number)

Use an iterable such as a string, list, tuple, set, dictionary, or range() instead.

Confusing the loop variable with the sequence

In for name in names, names is the complete iterable and name is only the current item. The loop variable is overwritten on every iteration, so after the loop only the last item is directly available.

Trying to modify a string character in place

Strings are immutable, meaning their individual characters cannot be replaced directly. Iterating over a string does not make assignments such as text[0] = "X" valid. Build a new string instead, or collect changed characters and join them afterward.

Unexpected output count

When processing text, count spaces, punctuation, and other characters as well as letters. Add a conditional test inside the loop if certain characters should be skipped.

Running and tracing examples

Use a Python interpreter or a script file to run each example. For a small loop, write down the iterable, the current loop-variable value, and the body result for each iteration. This makes the repeated execution order visible and helps locate indentation or range-boundary mistakes.

for item in iterable:
    statement
range(stop)
range(start, stop)
range(start, stop, step)

Summary

  • A for loop repeats its indented body once per item in an iterable.
  • Strings are sequences, so a string loop processes one character at a time, including spaces and punctuation.
  • The loop variable receives a new current item on every iteration.
  • range(stop), range(start, stop), and range(start, stop, step) generate integer progressions with an exclusive stop.
  • Use descriptive names, consistent indentation, and an accumulator when a running result is needed.

Next, you can explore the for loop alongside related topics such as conditional statements, lists, and while loops.