Python for loop

In Python, a for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code repeatedly for each item in the sequence.

Basic syntax of a for loop:


for item in sequence:
    # Code to execute for each item

Example 1: Loop through a list


fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(fruit)

Output:

apple
banana
orange

Example 2: Using range() to loop through a sequence of numbers


for i in range(5):
    print(i)

Output:

0
1
2
3
4

Note: range(5) generates a sequence of numbers from 0 to 4 (5 numbers).

Example 3: Loop through a string


name= "John"
for letter in name:
    print(letter)

Output:

J
o
h
n

Example 4: Using else with a for loop

The else clause is optional and will be executed after the loop finishes unless the loop is terminated by a break statement.


for i in range(3):
    print(i)
else:
    print("Finished!")

Output:

0
1
2
3
Finished!