Python For Loops 🔁
Iterating Over Sequences
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Unlike other languages, it works more like an iterator method.
🏭 Analogy: The Conveyor Belt
Imagine a factory conveyor belt carrying items (the list).
The for loop is a robot arm that picks up each item, one by one, and does something to it (prints it, calculates it, etc.).
It stops automatically when there are no more items on the belt.
✨ Basic Iteration
List
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)String
for x in "banana":
print(x)🔢 The range() Function
To loop through a set of code a specified number of times, we can use the range() function.
# range(stop)
for x in range(6):
print(x) # 0, 1, 2, 3, 4, 5
# range(start, stop)
for x in range(2, 6):
print(x) # 2, 3, 4, 5
# range(start, stop, step)
for x in range(2, 30, 3):
print(x) # 2, 5, 8, 11, ...🎯 Real-World Application: Bulk Actions
For loops are used to perform actions on a list of items, like sending emails to a list of users.
users = ["Alice", "Bob", "Charlie"]
for user in users:
print(f"Sending email to {user}...")🔚 Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is finished.
for x in range(6):
print(x)
else:
print("Finally finished!")⚠️ Important
The else block will NOT be executed if the loop is stopped by a break statement.
📦 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".
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)✨ Pro Tip: zip()
Use zip() to iterate over two lists at the same time!
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")