Skip to content
TrySitePrice

Python For Loop Examples

Best/Tutorial

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:

  1. Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
 print(fruit)

Output:

applernbananarncherry

  1. Iterating over a range:
for i in range(5):
 print(i)

Output:

0
1
2
3
4

  1. Iterating over a string:
word = "hello"
for letter in word:
 print(letter)

Output:

hrnernlrnlrno

  1. Using the enumerate function 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

  1. Using the zip function 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 6

These are just some examples, and you can use for loops in many different ways depending on your needs.