The 'for loop' in Python is kind of, like the 'while loop'. But the 'for loop' is way more powerful than the 'while loop'.
The 'for loop' has inbuilt features, by which you can reduce lines of code.
So far we have seen, how 'while loop' was used to print "Hello World" 5 times.
x = 1 while x <= 5: print("Hello World") x = x + 1
The same program could be reduced to two lines of code using the 'for loop'.
Let us see below.
Let us dive into the code directly and understand it eventually.
for x in range(5): print("Hello World")
And yes ! As said, we have reduced the code to two lines and that's all.
And the entire magic happens with the use of 'range(...)' function.
The 'range(...)' function is used with the 'for loop'. And the below statement,
for x in range(5):
Makes the 'for loop' run '5' times.
And the 'print(...)' statement,
print("Hello World")
Inside the 'for loop' is executed 5 times, printing "Hello World" 5 times on the screen.
Now, let us dissect the above 'for loop',
for x in range(5):
And it is a three step process :
So, if we convert the below 'for loop',
for x in range(5): print("Hello World")
To 'while loop',
x = 0 while x < 5: print("Hello World") x = x + 1
Let us look at another example to print the numbers, 0 to 5 using 'for loop'.
for x in range(6): print(x)
Even in this case, it is a two lines code.
The 'range(6)' function assigns the initial value of 'x' with '0'.
So in the 1st iteration,
The control comes the 'for loop' and since the value of 'range(6)' is 6, it checks, if the value of 'x' is less than '6'(i.e. 'x < 6').
In this case the value of 'x' is '0'. Which is less than '6'.
So, the control enters the 'for loop'.
and finds the print statement,
So, it prints the current value of 'x'(i.e. '0')
Next, the 'range(6)' function increments the value of 'x' by '1'. And the value of 'x' becomes '1'.
And the second Iteration starts.
Same way, the control comes the 'for loop' and checks, if the value of 'x' is less than '6'(i.e. 'x < 6').
In this case the value of 'x' is '1'. Which is less than '6'.
So, the control enters the 'for loop'.
And finds the print statement,
So, it prints the current value of 'x'(i.e. '1')
Similarly, the 'range(6)' function increments the value of 'x' by '1'. And the value of 'x' becomes '2'.
Similarly, the third, fourth and fifth Iteration continues incrementing the value of 'x', printing it.
Now, in the 7th Iteration, the control comes to the 'for loop' and checks, if the value of 'x' is less than '6'(i.e. 'x < 6').
And in this case the value of 'x' is '6'. Which is equal to '6'.
So, the condition fails and the loop exits.
So, the 'range(6)' function along with 'for loop' does a lot for us.
It initialises the value of 'x' with '0' initially. Then increments the value of 'x' with '1'. Also handles the conditional part (i.e. Continue the loop until 'x < 6').
But, what if we want to change the initial value of 'x' and also want to increment the value of 'x' with say, '2' or '3' or with any other value.
And luckily, 'range(6)' function gives us to change those as well.
Let us see them below :
In the above program, we have seen that the value of x was initialised to '0' initially.
However, the 'range(...)' function gives us the flexibility to change the initial value.
Say, we need to to print the numbers from 2 to 5.
Let us see in the below example.
for x in range(2, 6): print(x)
So, the 'range(2, 6)' function in the below 'for loop' :
Initialises the initial value of 'x' with '2', as the first parameter of 'range(2, 6)' function is '2'.
And as we have seen above, the conditional part is , 'continue to be in the for loop until the value of x is less than 6. i.e. x < 6'.
But the value of 'x' will be incremented by '1' in every Iteration.
Now, let us see, how can we change the incremental part, with some value other than '1'.
Now, let us see the code to print the below sequence :
So, if you see the above sequence, it starts with '2', ends with '8' and add '2' with the number to get the next number in the sequence.
Let us dive into the code.
for x in range(2, 9, 2): print(x)
Well ! It's that simple.
And the 'range(2, 9, 2)' function does the magic for us.
So far, we have seen, how to print numbers or a String. But there are also Collections like list, set, dictionary or tuple.
Let us see, how to Iterate through them.
Let's say, we have a List that stores the Cities.
And as we know, square brackets '[]' are used to represent a List.
Now, if we want to Iterate through the above List using 'for loop'.
cities = ["Mumbai", "Paris", "London"] for x in cities: print(x)
So, if we look at the above code, the 'for loop',
for x in cities: print(x)
Gets the values from the 'cities' list.
And in each Iteration, prints the value of 'x'.
Let us see the Iterations.
Below is the list (i.e. 'cities').
Or
And the for loop starts,
In the first Iteration, the first element is taken from the list 'cities' and put into the variable 'x'.
And the first element in the 'cities' list is 'Mumbai'. So, 'Mumbai' is put into 'x'.
And the value of 'x' is printed.
Similarly, in the second Iteration, the second element is taken from the list 'cities' and put into the variable 'x'.
And the second element in the 'cities' list is 'Paris'. So, 'Paris' is put into 'x' replacing 'Mumbai'.
And the value of 'x'is printed.
Similarly, in the third Iteration, the third element is taken from the list 'cities' and put into the variable 'x'.
And the third element in the 'cities' list is 'London'. So, 'Paris' is put into 'x' replacing 'Paris'.
And the value of 'x' is printed.
And in three Iterations, all the values of the List are printed.
Similarly, 'set', 'tuples' or 'dictionaries' can be Iterated using the same way.
Let us see the example of a 'set'.
numbers = {8, 4 ,1, 9} for x in numbers: print(x)
So, if you look at the above code, we have created a set named 'numbers'.
Then we have used the 'for loop' to Iterate through the set.
for x in numbers: print(x)
Now, if you look at the output, it is not in the same order.
i.e. The set is ,
And the output is in the below order,
That is because 'set' doesn't maintain the insertion sequence. And the above order is as expected in a 'set'.
The 'for loop' also gives us the flexibility to Iterate through a 'string'.
Let us see it in the below example.
city = "London" for x in city: print(x)
So, if you see the above code, we have a declared a string type variable 'city'.
Then, we have used the 'for loop' to Iterate through the string 'city'.
for x in city: print(x)
In each Iteration, a letter/alphabet is taken from the string 'city' and printed as output.
So, we have looked at various operations of the 'for loop'. Now, let us say, you want to print something after the 'for loop' has finished its execution.
Python gives us that flexibility as well with something called as an 'else' statement.
Say there is a list of four numbers, you want to Iterate. And once the Iteration is complete,you want to print, "Out of for loop".
Let us see with the below example :
numbers = [4, 5, 8, 9] for x in numbers: print(x) else: print("Out of for loop")
And if you look at the output, after all the numbers are printed, "Out of for loop" is printed when the loop has ended.
And that's because of the 'else' block,
else: print("Out of for loop")
With the 'for loop',
for x in numbers: print(x) else: print("Out of for loop")