Python offers various constructs for controlling program flow. The for loop provides a direct and efficient way to perform an action for each item within a sequence or collection. It is particularly useful when processing a known collection of items, one by one. Common uses include iterating over all elements in a list, all characters in a string, or repeating an action a specific number of times.
for Loop SyntaxThe fundamental structure of a for loop looks like this:
for variable_name in sequence:
# Code block to execute for each item
# Use variable_name to access the current item
statement1
statement2
# ...
Let's break this down:
for: The keyword that starts the loop.variable_name: A variable you choose (use a descriptive name) that will hold the current item from the sequence during each iteration (pass) of the loop.in: A keyword separating the loop variable from the sequence.sequence: The collection of items you want to iterate over. This could be a list, a string, or other iterable types we'll encounter later.:: The colon marks the end of the for statement line.if and while, the code that should run inside the loop must be indented. This block executes once for every item in the sequence.Lists are ordered collections, making them a perfect fit for for loops. Imagine you have a list of numbers and want to print each one.
temperatures = [19.5, 22.1, 18.0, 25.3]
print("Daily temperatures:")
for temp in temperatures:
print(f"Temperature recorded: {temp}°C")
print("\nLoop finished.")
Output:
Daily temperatures:
Temperature recorded: 19.5°C
Temperature recorded: 22.1°C
Temperature recorded: 18.0°C
Temperature recorded: 25.3°C
Loop finished.
In this example:
temperatures is the sequence (a list).temp is the loop variable.temp holds 19.5. The indented print statement executes.temp holds 22.1. The print statement executes again.25.3) is processed.print("\nLoop finished.")).Strings are sequences of characters. A for loop can iterate through each character in a string automatically.
user_name = "Alice"
print(f"Characters in the name {user_name}:")
for character in user_name:
print(f"- {character}")
Output:
Characters in the name Alice:
- A
- l
- i
- c
- e
Here, the loop variable character takes the value of each character ('A', then 'l', then 'i', etc.) in the string user_name during each pass.
range()Sometimes, you don't have an existing list or string to loop over, but you simply want to repeat an action a fixed number of times. Python's built-in range() function is incredibly helpful here. It generates a sequence of numbers that the for loop can iterate over.
range() can be used in a few ways:
range(stop): Generates numbers starting from 0 up to (but not including) the stop value.
print("Counting from 0 to 4:")
for i in range(5): # Generates 0, 1, 2, 3, 4
print(i)
Output:
Counting from 0 to 4:
0
1
2
3
4
Notice that range(5) produces numbers 0 through 4, which is 5 numbers in total. This zero-based behavior is common in programming. The variable i is conventionally used for simple loop counters, but you can use any valid variable name.
range(start, stop): Generates numbers starting from start up to (but not including) the stop value.
print("\nNumbers from 2 to 5:")
for num in range(2, 6): # Generates 2, 3, 4, 5
print(num)
Output:
Numbers from 2 to 5:
2
3
4
5
range(start, stop, step): Generates numbers starting from start, up to (but not including) stop, incrementing by step each time.
print("\nOdd numbers less than 10:")
for odd_num in range(1, 10, 2): # Generates 1, 3, 5, 7, 9
print(odd_num)
Output:
Odd numbers less than 10:
1
3
5
7
9
Using range() with a for loop is the standard way to perform actions like running a simulation for 100 steps, processing the first 10 items in a dataset, or simply printing a message multiple times.
Let's combine a for loop with what we learned about variables and operators to calculate the sum of numbers in a list.
scores = [88, 92, 75, 98, 85]
total_score = 0 # Initialize accumulator variable
for score in scores:
total_score = total_score + score # Add current score to total
print(f"The list of scores is: {scores}")
print(f"The total score is: {total_score}")
Output:
The list of scores is: [88, 92, 75, 98, 85]
The total score is: 438
In this example, total_score acts as an accumulator. It starts at 0, and in each iteration, the current score from the scores list is added to it.
for vs. whilefor loop when you want to iterate over every item in a known sequence (like a list, string, or range) or when you need to repeat an action a specific number of times. It handles managing the iteration process (getting the next item, stopping at the end) for you.while loop when you need to repeat an action as long as a certain condition remains true, and you don't necessarily know beforehand how many times the loop will run. You typically need to manage the condition explicitly within the loop.The for loop provides a concise and readable way to process items in sequences, making it one of the most frequently used control flow structures in Python. As you learn about more complex data structures like dictionaries and tuples in the next chapter, you'll see that for loops work well with them too.
Was this section helpful?
for statement, iteration over sequences, and the range() function with clear examples.for loops, iterators, and sequences in Python.for loops.© 2026 ApX Machine LearningEngineered with