What is a For Loop in Python?
A Python for loop is used to iterate over sequences like lists, tuples, strings, dictionaries, or even ranges of numbers. Unlike some other languages where for loops iterate using counters, Python’s for loop works directly with elements in a sequence.
Why Use For Loops?
- Efficiency: Ideal for processing data in collections like lists or strings.
- Readability: Makes code concise and easy to understand.
- Versatility: Can be used with any iterable object.
Syntax of a For Loop
for variable in sequence:
# Code block to execute
- variable: A temporary placeholder for each element in the sequence.
- sequence: Any iterable object such as a list, tuple, string or range.
Example: Iterating Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Iterating Over Different Data Types
1. Strings
name = "Python"
for char in name:
print(char)
Output:
P
y
t
h
o
n
2. Tuples
numbers = (1, 2, 3, 4)
for num in numbers:
print(num)
Output:
1
2
3
4
3. Dictionaries
You can iterate over keys, values, or both using dictionary methods.
student = {"name": "John", "age": 20, "grade": "A"}
for key, value in student.items():
print(f"{key}: {value}")
Output:
name: John
age: 20
grade: A
4. Ranges
The range() function generates a sequence of numbers.
for i in range(5): # Iterates from 0 to 4
print(i)
Output:
0
1
2
3
4
Using Else with For Loops
Python allows an optional else block with a for loop. The else block executes after the loop finishes, provided it wasn’t terminated by a break.
Example:
for num in range(3):
print(num)
else:
print("Loop completed successfully!")
Output:
0
1
2
Loop completed successfully!
Using Break and Continue in For Loops
Break Statement
Exits the loop prematurely.
for num in range(10):
if num == 5:
break
print(num)
Output:
0
1
2
3
4
Continue Statement
Skips the current iteration and continues with the next one.
for num in range(5):
if num == 2:
continue
print(num)
Output:
0
1
3
4
Nested For Loops
You can use a for loop inside another for loop to handle nested data structures.
Example:
matrix = [[1, 2], [3, 4], [5, 6]]
for row in matrix:
for element in row:
print(element)
Output:
1
2
3
4
5
6
Practical Examples of For Loops
Example 1: Sum of a List
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("Total:", total)
Output:
Total: 15
Example 2: Generating Multiplication Table
num = 3
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Output:
3 x 1 = 3
3 x 2 = 6
...
3 x 10 = 30
Example 3: Filtering Even Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in numbers:
if num % 2 == 0:
print(f"Even number: {num}")
Output:
Even number: 2
Even number: 4
...
Even number: 8