Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




PYTHON - FOR LOOP


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.


Example :


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.


Example of 'for loop' using the range() function


Let us dive into the code directly and understand it eventually.


Example :


for x in range(5):
    print("Hello World")

Output :



  Hello World
  Hello World
  Hello World
  Hello World
  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 :

  1. The 'range(5)' function assigns the value of 'x' with '0'.
  2. With each iteration of for loop, the value of x is incremented by 1.
  3. And, since the 'range(5)' function has the value '5', the 'for loop' continues until the value of 'x' is less than 5(i.e. The range is from 0 to 4).

So, if we convert the below 'for loop',


Example :


for x in range(5):
    print("Hello World")



To 'while loop',


Example :


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'.


Example :


for x in range(6):
    print(x)

Output :



  0
  1
  2
  3
  4
  5

Even in this case, it is a two lines code.


The 'range(6)' function assigns the initial value of 'x' with '0'.


java_Collections

So in the 1st iteration,


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'.


for x in range(6):

and finds the print statement,


print(x)

So, it prints the current value of 'x'(i.e. '0')


Output :



  0

Next, the 'range(6)' function increments the value of 'x' by '1'. And the value of 'x' becomes '1'.


java_Collections

And the second Iteration starts.


2nd Iteration


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'.


for x in range(6):

And finds the print statement,


print(x)

So, it prints the current value of 'x'(i.e. '1')


Output :



  0
  1

Similarly, the 'range(6)' function increments the value of 'x' by '1'. And the value of 'x' becomes '2'.


java_Collections

Similarly, the third, fourth and fifth Iteration continues incrementing the value of 'x', printing it.


3rd Iteration


Output :



  0
  1
  2

java_Collections

4th Iteration


Output :



  0
  1
  2
  3

java_Collections

5th Iteration


Output :



  0
  1
  2
  3
  4

java_Collections

6th Iteration


Output :



  0
  1
  2
  3
  4
  5

java_Collections

7th Iteration


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.


for x in range(6):

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 :


The 'range(...)' function with custom initial value


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)



Output :



  2
  3
  4
  5

So, the 'range(2, 6)' function in the below 'for loop' :


for x in range(2, 6):

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'.


The 'range(...)' function with custom incremental part


Now, let us see the code to print the below sequence :


2  4  6  8

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.


Example :


for x in range(2, 9, 2):
    print(x)


Output :



  2
  4
  6
  8

Well ! It's that simple.


And the 'range(2, 9, 2)' function does the magic for us.


for x in range(2, 9, 2):

  1. The first parameter in the 'range(2, 9, 2)' function initialises the value of initial value of 'x' with '2'.
  2. The second parameter in the 'range(2, 9, 2)' function is the conditional part and determines, how long the loop should run.

    In this case, since the last value to be printed is '8'. We have put the second parameter as '9'(i.e. Continue to be in the loop until x < 9).

    Just remember, the conditional part should be one more than the value to be printed(i.e. '9' in this case).
  3. The third parameter in the 'range(2, 9, 2)' function is the incremental part. And we have incremented values at each Iteration with '2'.

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.


For Loop to Iterate through Collections


Let's say, we have a List that stores the Cities.


And as we know, square brackets '[]' are used to represent a List.


cities = ["Mumbai", "Paris", "London", "Delhi"]

Now, if we want to Iterate through the above List using 'for loop'.


Example :


cities = ["Mumbai", "Paris", "London"]
for x in cities:
    print(x)


Output :



  Mumbai
  Paris
  London

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').


cities = ["Mumbai", "Paris", "London"]

Or


java_Collections

And the for loop starts,


for x in cities:

1st Iteration


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'.


java_Collections

And the value of 'x' is printed.


Output :



  Mumbai

2nd Iteration


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'.


java_Collections

And the value of 'x'is printed.


Output :



  Mumbai
  Paris

3rd Iteration


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'.


java_Collections

And the value of 'x' is printed.


Output :



  Mumbai
  Paris
  London

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'.


Example :


numbers = {8, 4 ,1, 9}
for x in numbers:
    print(x)


Output :



  8
  1
  4
  9

So, if you look at the above code, we have created a set named 'numbers'.


numbers = {8, 4 ,1, 9}

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 ,


8,  4,  1,  9

And the output is in the below order,


8  1  4  9

That is because 'set' doesn't maintain the insertion sequence. And the above order is as expected in a 'set'.


Iterating through a String


The 'for loop' also gives us the flexibility to Iterate through a 'string'.


Let us see it in the below example.


Example :


city = "London"
for x in city:
    print(x)


Output :



  L
  o
  n
  d
  o
  n

So, if you see the above code, we have a declared a string type variable 'city'.


city = "London"

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.


Else with for loop


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 :


Example :


numbers = [4, 5, 8, 9]
for x in numbers:
    print(x)
else:
    print("Out of for loop")


Output :



  4
  5
  8
  9
  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")