Natan
Natan

Reputation: 71

Nested loop not printing the first element but going to 2nd element?

I have a very simple piece of code but it's driving me nuts to understand the logic.

for a in range(6):
   print("\t\t")
for j in range(a):
    print(a, end=" ")

The output is:

1       
2 2         
3 3 3       
4 4 4 4         
5 5 5 5 5

the first value to be printed is supposed to be 0 since the range(6) starts from 0 and a and j wrapped in for loops both are supposedly getting 0 as first element but it starts from 1 instead.

Upvotes: 0

Views: 794

Answers (2)

alani
alani

Reputation: 13049

The value of a is the number of iterations of the inner loop. (Note that the question should have the j loop indented, so that it is inside the a loop, in order to get the output shown.)

On the first iteration, a is 0, and then range(0) will give an empty sequence, which give zero iterations when iterating over it. (Specifically a StopIteration will occur the first time a value is fetched.)

On the next iteration of the outer loop, there will be one j value when iterating, and so forth.

So 0 is printed 0 times (i.e. not at all), then 1 is printed once, 2 is printed twice, ... , 5 is printed 5 times.

You are not using the values of j at all, but they will be:

  • when a is 0: no iterations
  • when a is 1: j is 0 only
  • when a is 2: j is 0, 1
  • ... etc, up to ...
  • when a is 6: j is 0, 1, 2, 3, 4, 5

Note that in fact it is conventional to use a variable name _ for a loop variable whose value you do not use (at least assuming that it not inside a loop already using _). If you adhere to this convention (i.e. use _ instead of j) and also fix the indentation, then your code might look like:

for a in range(6):
    print("\t\t")
    for _ in range(a):
        print(a, end=" ")

Upvotes: 1

Aleksander Ikleiw
Aleksander Ikleiw

Reputation: 2675

That comes, because the for loop in range 0 will not be executed. You can not execute something if that has to go 0 times. To make it run as you would like to be, you would have to write following code:

for a in range(6):
   print("\t\t")
   for j in range(a + 1):
       print(a, end=" ")

Upvotes: 2

Related Questions