Python For Loop Examples
A for loop in Python is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. Here are some examples of using a for loop in Python:
- Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
applernbananarncherry- Iterating over a range:
for i in range(5):
print(i)Output:
0
1
2
3
4- Iterating over a string:
word = "hello"
for letter in word:
print(letter)Output:
hrnernlrnlrno- Using the
enumeratefunction to get the index and the item:
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)Output:
0 applern1 bananarn2 cherry- Using the
zipfunction to iterate over multiple lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for x, y in zip(list1, list2):
print(x, y)Output:
1 4
2 5
3 6These are just some examples, and you can use for loops in many different ways depending on your needs.
