Understanding Python For Loops: Iterating Over Sequences
Explore how to use the for
loop in Python to iterate over sequences like lists, tuples, dictionaries, sets, and strings. Unlike traditional for loops in other languages, Python’s for
loop functions more like an iterator method, allowing you to execute statements for each item in a collection efficiently.
Python For Loops
A for
loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string).
This is different from the for
keyword in other programming languages. It works more like an iterator method found in object-oriented programming languages.
With the for
loop, we can execute a set of statements once for each item in a list, tuple, set, etc.
Example: Print each fruit in a list
fruits = ["apple", "mango", "grape"]
for x in fruits:
print(x)
apple
mango
grape
The for
loop does not require an indexing variable to be set beforehand.
Looping Through a String
Even strings are iterable objects; they contain a sequence of characters.
for x in "orange":
print(x)
o
r
a
n
g
e
The break Statement
The break
statement allows us to stop the loop before it has looped through all the items.
Example: Exit the loop when x is "mango"
fruits = ["apple", "mango", "grape"]
for x in fruits:
print(x)
if x == "mango":
break
apple
mango
Example: Exit the loop when x is "mango", but this time the break comes before the print
fruits = ["apple", "mango", "grape"]
for x in fruits:
if x == "mango":
break
print(x)
apple
The continue Statement
The continue
statement stops the current iteration of the loop and continues with the next.
Example: Do not print mango
fruits = ["apple", "mango", "grape"]
for x in fruits:
if x == "mango":
continue
print(x)
apple
grape
The range() Function
To loop through a set of code a specified number of times, we can use the range()
function.
The range()
function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Example: Using the range() function
for x in range(5):
print(x)
0
1
2
3
4
Note that range(5)
is not the values of 0 to 5, but the values 0 to 4.
Example: Using the start parameter
for x in range(3, 6):
print(x)
3
4
5
Example: Increment the sequence with 3 (default is 1)
for x in range(2, 12, 3):
print(x)
2
5
8
11
Else in For Loop
The else
keyword in a for loop specifies a block of code to be executed when the loop is finished.
Example: Print all numbers from 0 to 4, and print a message when the loop has ended
for x in range(5):
print(x)
else:
print("Finally finished!")
0
1
2
3
4
Finally finished!
Note: The else block will NOT be executed if the loop is stopped by a break
statement.
Example: Break the loop when x is 2, and see what happens with the else block
for x in range(5):
if x == 2: break
print(x)
else:
print("Finally finished!")
0
1
Nested Loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".
Example: Print each adjective for every fruit
adj = ["small", "medium", "large"]
fruits = ["apple", "mango", "grape"]
for x in adj:
for y in fruits:
print(x, y)
small apple
small mango
small grape
medium apple
medium mango
medium grape
large apple
large mango
large grape
The pass Statement
for
loops cannot be empty, but if you for some reason have a for
loop with no content, put in the pass
statement to avoid getting an error.
Example:
for x in [0, 1, 2]:
pass