A for loop in Python is used to repeat a block of code for each element in a sequence. It works with
lists, tuples, sets, dictionaries, strings, ranges, and nested structures. Indentation (4 spaces) is
required to define the loop body. This document explains each type of loop with definition, syntax,
examples, real-life use cases, outputs, tips, and a summary.
1. For Loop with List
Definition: Iterates over each element in a list.
Use: Useful for processing ordered data.
Syntax:
for item in list:
# code
Example (Basic):
fruits = ["apple", "banana", "cherry"]
for f in fruits:
print(f)
Output:
apple
banana
cherry
Real-Life Example (Shopping Cart):
cart = [("Shirt", 1000), ("Shoes", 2000)]
total = 0
for item, price in cart:
print(item, ":", price)
total += price
print("Total =", total)
Output:
Shirt : 1000
Shoes : 2000
Total = 3000
Tip: Lists are great for processing multiple values in order.
2. For Loop with Tuple
Definition: Iterates over each element in a tuple (immutable).
Use: Useful for fixed collections.
Syntax:
for item in tuple:
# code
Example (Basic):
numbers = (10, 20, 30)
for n in numbers:
print(n)
Output:
10
20
30
Real-Life Example (Coordinates):
coordinates = [(2, 3), (4, 5)]
for x, y in coordinates:
print("x:", x, "y:", y)
Output:
x: 2 y: 3
x: 4 y: 5
Tip: Tuples are good when data should not be modified.