Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using python range() with for loop but situation is 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?

What I have tried:

Python
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
Posted
Updated 15-Jul-18 8:41am

If you want to find out exactly how this code work, use the debugger. It's there to debug YOU and your understanding of the code.

It appears the i loop executes twice in a row because it doesn't. The inner j loop executes but range returns an array of values from i - 1 to 0, with the upper limit of 0 being non-inclusive.

On the first iteration of i, that would be range(1 - 1, 0, -1), which will return no values for the j loop.

This is the expected behavior.
 
Share this answer
 
v3
Look at the values of your inner loop. The first time it runs the variable i holds the value 1. So the loop will not run since i - 1 is zero, and the loop is defined to run from values zero to zero.
 
Share this answer
 
Quote:
why the outer loop run twice before the inter loop get a chance to run?

For a good explanation, read the documentation:
4. Built-in Types — Python 3.7.0 documentation[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900