A for loop in Python is used to iterate over a sequence (which can be a list, tuple, string, or range) or any other iterable object. It allows you to execute a block of code multiple times, once for each item in the sequence. Here's the basic syntax of a for loop in Python:
for item in iterable:
# Perform actions using `item`
Examples:
Iterating over a List:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Iterating over a String:
word = "hello"
for letter in word:
print(letter)
Output:
h
e
l
l
o
Using range():
The range() function is often used in for loops to generate a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
You can also specify start and end points, and an optional step:
for i in range(2, 10, 2):
print(i)
Output:
2
4
6
8
Enumerating a List:
When you also need the index while iterating over a list, you can use enumerate():
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
Iterating over a Dictionary:
You can iterate over keys, values, or key-value pairs:
ages = {'Alice': 25, 'Bob': 30, 'Charlie': 35}
for name, age in ages.items():
print(name, age)
Output:
Alice 25
Bob 30
Charlie 35
These examples demonstrate how versatile and easy-to-use for loops are in Python for various types of data and iterables.