2

What is the output of the following nested control structure in Python when executed?

for x in range(3):
    for y in range(x):
        print x,y

I know the answer is

1 0
2 0
2 1

But it is not clear for me why it is this output.
I know that the range(3) function would give you {0, 1, 2} so why is not the first output 0 0 instead of 1 0?

2
  • 3
    The interval [0, 0) is empty. Commented Dec 16, 2015 at 14:56
  • 1
    @Kay, +1 for basing this in mathematics. Also consider the manual, as this is one of the examples presented for the range() function. Commented Dec 16, 2015 at 15:00

3 Answers 3

8

Because range(0) returns an empty list [], so the inner loop does nothing the first time it is run.

Sign up to request clarification or add additional context in comments.

Comments

8

Lets go through this

First run

x = 0
range(0) is []
the print is never reached

Second Run

x = 1
range(1) is [0] <-- one element
print is called once with 1 0

Third Run

x = 2
range(2) is [0,1] <-- two elements
print is called twice with 2 0 and 2 1

Comments

0

Yes range(x) is [0,1,2,3,...x-1] In short, range(x) is a list of x elements starting at 0 and incrementing. As previously mentioned, this causes the first run of the second loop to never execute.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.