Home > Back-end >  Question about double for loops and ranges
Question about double for loops and ranges

Time:01-03

Since I am a beginner to python I was confused as to why j results to this: 0 1 0 1 2 when doing the code below. From my understanding I thought, i represents 0-3 so wouldn't j represents the numbers 0-3 as well.

for i in range(4):
    for j in range(i):
        print(j)

CodePudding user response:

Your first for loop goes from 0 to 3.

So i is 0, then 1, then 2, then 3.

J is going to be 0, then 1, then 2, then 3.

So printing j in range (0) does nothing, because range(0) is nothing.

Then you print j in range(1), which prints 0

Then you print j in range(2) which prints 0, 1

Lastly you print j in range (3) which prints 0, 1, 2

CodePudding user response:

There are 4 iterations of the outer loop, for i set to 0, 1, 2, and 3.

The first one does nothing, as range(0) is an empty sequence.

The second one outputs 0, the only value in range(1).

The third outputs 0 and 1, the values in range(2).

The last prints 0, 1, and 2, the values in range(3).

The key is that the inner call to range uses the current value of i to produce a range of values that does not include i itself.

CodePudding user response:

In this example for loop for i in range(4) will run while i is smaller than stop value which is in this case 4 (The last run of loop is going to be when i is 3). The default starting value for variable in range function is 0. If you pass two arguments to range function, first will be starting value, and second will be stop value (when variable isn't less then stop value, loop isn't going to run anymore). With every iteration, the starting value will increase by 1. You can change that number by passing third argument to range function. If start and stop value are same, for example 0 and 0, for loop won't run.

It's same with nested for loops, like in your example. Hope I made you for loops little bit easier.

Note: I am not so good at English.

CodePudding user response:

The same way i represents 0-3 (which is 1 less than the stop arg 4); j will take values upto the stop param (i) -1.

On the iteration where i == 3, j will only go upto 2 (i.e one less than i).

  • Related