Reputation: 91
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?
Upvotes: 2
Views: 1386
Reputation: 1
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.
Upvotes: 0
Reputation: 4255
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
Upvotes: 8
Reputation: 2242
Because range(0) returns an empty list []
, so the inner loop does nothing the first time it is run.
Upvotes: 8