Python for Loops



The For loop is used for sequential traversal.

It can be used to traverse string or array.

Iteration over a sequence is called traversal.

The For loop is used to iterate over a sequence(list, string tuple,  dictionary, set, etc).


Syntax

for var in sequence:
    body of forloop

The var will take the value of the item inside the sequence on each iteration.

Here the sequence is maybe list, string tuple,  dictionary, set, etc


Example 1

x = ["Python", "Java", "Django", "Angular"]
for i in x:
    print(i)

Output

Python
Java
Django
Angular

Example 2

x = "Python"
for i in x:
    print(i)

Output

P
y
t
h
o
n

Break keyword in for Loop

Python Break keyword used to terminate the loop.


Example

x = ["Python", "Java", "Django", "Angular"]
for i in x:
    if i == "Django":
        break
    print(i)

Output

Python
Java

Continue keyword in for Loop

The continue keyword skips the current repetition of a loop and continues with the next repetition.


Example

x = ["Python", "Java", "Django", "Angular"]
for i in x:
    if i == "Django":
        continue
    print(i)

Output

Python
Java
Angular

Else keyword ​​​​​​ in for Loop

We can also use else statement with for loop but it is not compulsory.

Else part will execute if the items in the sequence used in for loop exhausts.


Example

x = ["Python", "Java", "Django", "Angular"]
for i in x:
    print(i)
else:
    print("For Loop Completed!")

Output

Python
Java
Django
Angular
For Loop Completed!

range() function in for loop

range() function is used to generate a sequence of numbers. The sequence of range function is range(start,stop,step).

The default step is 1.


Example 1

for i in range(1, 11):
    print(i)

Output

1
2
3
4
5
6
7
8
9
10

Example 2

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

Output

0
1
2
3
4

Example 3

for i in range(1, 11, 2):
    print(i)

Output

1
3
5
7
9

How to Access Index in for Loop?


Example

x = ["Python", "Java", "Django", "Angular"]
for i in range(len(x)):
    print(i, x[i])

Output

0 Python
1 Java
2 Django
3 Angular

Nested for Loop

A loop inside another loop is called a nested loop.


Example

x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in x:
    for v in i:
        print(v)

Output

1
2
3
4
5
6
7
8
9

How to Unpacking in a for loop?

We unpack the tuple in this Example


Example 1

x = [(1, 2), (3, 4), (5, 6)]
for (a, b) in x:
    print(a, b)

Output

1 2
3 4
5 6

Example 2

This Example for Dictionary 

x = {"name": "Denny", "subject": "Python", "age": 21}
for a, b in x.items():
    print(a, b)

Output

name Denny
subject Python
age 21