In this article, we’ll learn how to use a for loop in python. This is also used for iterations like in while loop but Python for loop is used to iterate over a sequence like a list, tuple, strings, or other objects.
for value in sequence: statement
To run the for loop, we need to make sure to use proper indentation. Loop will continue to run until we reach the last value in that sequence. Let’s understand this with a simple example.
var = [1, 2, 3, 4, 5, 6] for i in var: print(i)
1 2 3 4 5 6
Let’s check out another example using only string values.
var = 'TECHIE' for i in var: print(i)
T E C H I E
We can also print a sequence of values like in while loop using
range() function. We just need to provide the end value or start and end value to the function. For example,
range(5) will give you output from 0 to 4.
Syntax for start and end value will be
range(start_value, end_value). We can also provide a step size and the syntax will be
range(start_value, end_value, step_size).
for i in range(1, 5): print(i) # With step size of 2 for i in range(1, 6, 2): print(i)
1 2 3 4 1 3 5
Nested for Loop
Using a for loop inside a for loop is known as nested for loop. Loop inside a for loop is called the inner loop.
x = ["Hello", "Bye"] y = ["John", "Blake"] for i in x: for j in y: print(i, j)
Hello John Hello Blake Bye John Bye Blake
In the above example, first the outer loop was executed and then the inner loop twice as there were 2 elements in y. After the inner loop completed, it again went back to outer loop to run for the second time as there being 2 elements in the list.
for loop with Else
Just like we used else statement with while loop, we can use else with for loop as well. Else statement will execute once all the iterations are exhausted.
for i in range(4): print(i) else: print("This is Else")
0 1 2 3 This is Else