David Ma
David Ma

Reputation: 29

why Python range function in for loop running twice

situation: 2 loops, expect the outer loop run once, then inter loop runs completely, then outer loop runs its 2nd... question: why the outer loop run twice before the inter loop get a chance to run?

Code:

def sort(a_list):
    for i in range(1,len(a_list)):
        print("i=",i)
        for j in range(i-1,0,-1):
            print("j=",j)

Test: L=[9,6,1,3]

sort(L)

Result:

i= 1
i= 2   # here, the outer lopp ran twice then inter loop began.
j= 1
i= 3
j= 2
j= 1

Upvotes: 0

Views: 3287

Answers (2)

Shreyan Mehta
Shreyan Mehta

Reputation: 550

Because here in inner loop for the first iteration it would be

For j in range(1-1,0,-1):

Which equates to

For j in range(0,0,-1):

That range is an empty range so at i=1 inner loop won't run since condition evaluate to false

Upvotes: 0

nuric
nuric

Reputation: 11225

It's because when i = 1 the inner loop becomes range(0,0,-1) which is empty. So you don't print anything and move onto i = 2.

Upvotes: 3

Related Questions