The for
loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) and execute a block of code for each item in the sequence. Here are some examples to help you understand how for
loops work in Python:
- Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This will output:
apple
banana
cherry
- Iterating over a range of numbers:
for i in range(5):
print(i)
This will output:
0
1
2
3
4
- Using
enumerate()
to get the index and value of items in a list:
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
This will output:
0 apple
1 banana
2 cherry
- Iterating over a dictionary:
person = { "name": "John", "age": 30, "city": "New York" }
for key, value in person.items():
print(key, value)
This will output:
name John
age 30
city New York
These are just a few examples of how you can use for
loops in Python. You can use for
loops with any sequence type and perform different actions for each item in the sequence.