Python For Loop

A for loop is used to execute a block of code repeatedly for a specific number of times or until some conditions are true.

A for loop is commonly used to iterate over items of list, tuple, dictionaries, sets, string letters, etc.

Example 1

A program to print a list of string items using for a for loop:


fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
for i in fruits:
    print(i)
  
Output
grapes
mango
apple
pineapple
banana
Example 2

Print numbers from 1 to 10:


for i in range(1, 11):
    print(i)
  
Output
1
2
3
4
5
6
7
8
9
10
Example 3

Print negative numbers from -10 to -1:


start, end = -10, 0           
for num in range(start, end): 
    if num < 0:               
        print(num, end = " ")
  
Output
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

The break statement

The break statement is used to terminate the loop before the looping through all items is complete.

Example

Terminate the loop when i is mango:


fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
for i in fruits:
    #exit loop when i is mango
    if(i == "mango"):
        break
    print(i)
print("End of program")
  
Output
grapes
End of program

The continue statement

The continue statement is used to skip the current loop and continue with the next loop.

Example

Skip when i is "apple"


fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
for i in fruits:
    #go to next loop if the current value of i is apple
    if(i == "apple"):
        continue
    print(i)
print("End of program")
  
Output
mango
pineapple
banana
End of program

The pass statement

The for loop cannot iterate over an empty items. Therefore, to prevent error from happening in such cases, the pass statement is used.

Example

Iterate over an empty list:


fruits = []
for i in fruits:
    pass
  

The range function

The range() function returns a sequence of numbers starting from 0. You can use the range() function with the for loop to repeatedly run a block of code a specified number of times.

Example

fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
for i in range(5):
    print(fruits[i])
  
Output
grapes
mango
apple
pineapple
banana

Nested for loop

The nested for loop is a loop within a loop. In a nested loop, the first pass of the outer loop triggers the inner loop, the inner loop executes to completion.

Example

x = ["a", "b", "c", "d", "e"]
y = [1, 2, 3, 4, 5]
for i in x:
    for j in y:
        print(i,j)
  
Output
a 1
a 2
a 3
a 4
a 5
b 1
b 2
b 3
b 4
b 5
c 1
c 2
c 3
c 4

The range function

The range() function returns a sequence of numbers starting from 0. You can use the range() function with the for loop to repeatedly run a block of code a specified number of times.

Example

fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
for i in range(5):
    print(fruits[i])
  
Output
grapes
mango
apple
pineapple
banana