In Python, a for statement is used to loop through any iterable object, including sequences such as lists, strings and dictionaries.
For loop Syntax
for item in sequence:
# Run this block of code
Read the above code as: for each item in sequence, run this block of code.
Example: Iterating Through a List
Let's iterate through a list of three items:
# A list of three AI models
models = ["Fable", "ChatGPT", "Gemini"]
# Access items of the list one by one
for model in models:
print(model)
print("---")
Output
Fable --- ChatGPT --- Gemini ---
Read the above code as: for each model in the models list, run this code:
print(model)
print("---")
Since the models list has three items, the value of model will be:
"Fable"in the first iteration."ChatGPT"in the second iteration."Gemini"in the third iteration.
Note: If you find a program hard to follow, click the Visualize button below any code example to run the code line by line and see what happens at every step.
Indentation in Loop
Indentation (spaces at the beginning of a statement) is part of the Python syntax. We use indentation to specify a block of code, such as the body of a loop. For example,
numbers = [1, 2, 3]
for num in numbers:
print(f"Processing: {num}")
print(f"Done with: {num}")
# This statement is outside the loop
print('All done')
Output
Processing: 1 Done with: 1 Processing: 2 Done with: 2 Processing: 3 Done with: 3 All done
Here, print('All done') is outside the loop. Therefore, this statement is executed only once at the end.
For Loop with Python range()
One common task in programming is to repeat code a certain number of times (like 10 times). For example, displaying 10 products on a page from a list of 100 products.
You can perform such tasks by using the range() function in a for loop. This is because the range() function returns a sequence of numbers. For example,
# Generate numbers from 1 to 4
values = range(1, 5)
Here, range(1, 5) returns a sequence of 1, 2, 3 and 4. Since the range() function returns a sequence of numbers, we can iterate over it. For example,
# Iterate from i = 1 to i = 10
for i in range(1, 11):
print(f"Displaying product {i}")
Output
Displaying Product 1 Displaying Product 2 ... Displaying Product 10
Example: Iterating Through a String
If we iterate through a string, we get the individual characters of the string one by one.
language = 'Python'
for x in language:
print(x)
Output
P y t h o n
Break and continue Statements
The break and continue statements are used to alter the flow of loops.
The break Statement
The break statement terminates the for loop immediately when it's encountered. For example,
for num in range(1, 11):
if num == 3:
break
print(num)
Output
1 2
range(1, 11) creates a sequence of numbers from 1 to 10. However, when num equals 3, the break statement executes, which terminates the loop immediately. That's the reason why only 1 and 2 are printed.
The continue Statement
The continue statement skips the current iteration of the loop and continues with the next iteration. For example,
for num in range(1, 6):
if num == 3:
continue
print(num)
Output
1 2 4 5
range(1, 6) creates a sequence from 1 to 5. However, when num equals 3, the continue statement executes, which skips the remaining code after it and continues to the next iteration. That's why 3 is not displayed in the output.
You can find more information on break and continue statements here.
For Loop with else
A for loop can have an optional else clause. This feature is unique to Python and is not found in most other languages.
The code inside the else clause is executed when the loop is finished. However, if the loop is terminated by using a break statement, the else block will not be executed. For example,
stock = ['Laptop', 'Keyboard', 'Mouse']
order = input("Enter the product you want to buy: ")
for product in stock:
if product == order:
print(f"{order} is available. Adding to cart.")
break
else:
print(f"Sorry, {order} is out of stock.")
Output 1
Enter the product you want to buy: Laptop Laptop is available. Adding to cart.
Output 2
Enter the product you want to buy: Monitor Sorry, Monitor is out of stock.
The logic here is:
- If the product is in stock, the
breakstatement terminates the loop and out of stock message insideelseis not displayed. - If the product is not in stock, out of stock message is displayed, as the
breakstatement is never encountered.
Using for Loop Without Using Items
If you don't intend to use items of a sequence inside the loop, it is clearer to use the _ (underscore) as the loop variable. For example,
# Iterate from i = 0 to 3
for _ in range(0, 4):
print("Hi")
Output
Hi Hi Hi Hi
Here, the loop iterates four times and prints "Hi" in each iteration.
Example: Sum of Natural Numbers
Now that we know how a for loop works, let's create an interesting program to calculate the sum of natural numbers.
What we'll do in this program is find the sum of numbers from 1 to 10.
# Initial value of sum is 0
total = 0
# Iterate from i = 1 to 10
for i in range(1, 11):
total += i # Add i to total in each step
print(f"Total = {total}")
Output
Total = 55
Here, the loop iterates from i = 1 to 10. In each iteration, we add the current value of i to the total variable. The final total is the sum of numbers from 1 to 10.
Again, if you're having trouble following this program, click Visualize above to see exactly what happens at each step.
Nested for loops
A loop can also contain another loop inside it, known as a nested loop. In a nested loop, the inner loop is executed once for each iteration of the outer loop.
attributes = ['Electric', 'Fast']
cars = ['Tesla', 'Porsche', 'Mercedes']
# Outer loop
for attribute in attributes:
# Inner loop
for car in cars:
print(attribute, car)
# This statement is outside the inner loop
print("-----")
Output
Electric Tesla Electric Porsche Electric Mercedes ----- Fast Tesla Fast Porsche Fast Mercedes -----