The for
loop in Python is used to iterate over sequences such as lists, strings, tuples, dictionaries, or anything that's iterable. It's one of the most commonly used control flow tools in programming.
Basic Syntax
for variable in iterable:
# code block to execute
Let’s explore how the for
loop works with different examples to build a solid understanding.
Example 1: Looping Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This prints each fruit in the list one by one.
Example 2: Using range()
with for Loop
for i in range(5):
print("Number:", i)
range(5)
gives numbers from 0 to 4.
Example 3: Iterating Over a String
for letter in "Python":
print(letter)
Each character of the string is printed separately.
Example 4: Looping Through a Tuple
colors = ("red", "green", "blue")
for color in colors:
print(color)
Tuples can be looped just like lists.
Example 5: Using for Loop with Dictionary
student = {"name": "Amit", "age": 20}
for key in student:
print(key, ":", student[key])
You can iterate over keys and access values using dict[key]
.
Example 6: Nested for Loop
for i in range(2):
for j in range(3):
print(i, j)
Useful for grid-like or tabular operations.
Example 7: Loop with Conditional Logic
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(num, "is even")
Condition inside the loop adds control.
Example 8: Using break
in a for Loop
for i in range(10):
if i == 5:
break
print(i)
Stops the loop when i
becomes 5.
Example 9: Using continue
in a for Loop
for i in range(5):
if i == 2:
continue
print(i)
Skips 2 but continues the rest of the loop.
Example 10: Using else
with for Loop
for i in range(3):
print(i)
else:
print("Loop completed")
The else
block runs after the loop ends (unless broken).
When to Use for
Loop
- When you know the number of iterations in advance.
- To iterate over lists, strings, tuples, dictionaries, or files.
- When working with counters or collections in general.
The for
loop is a powerful tool in Python that helps you automate repetitive tasks and work efficiently with data structures. Mastering it unlocks the ability to handle collections with ease.