My question concerns the output of this statement:
for x in range(4), y in range(4):
print x
print y
Results in:
[0, 1, 2, 3]
2
True
2
It seems there is a comparison involved, I just can't figure out why the output is structured like this.
My guess is that you're running this from an interactive console, and already had y defined with a value of 2 (otherwise, you'd get NameError: name 'y' is not defined). That would lead to the output you observed.
This is due to for x in range(4), y in range(4): actually being equivalent to the following when evaluated:
for x in (range(4), y in range(4)):
which reduces to...
for x in ([0,1,2,3], 2 in range(4)):
which again reduces to...
for x in ([0,1,2,3], True):
This then results in 2 iterations of the for loop, since it iterates over each element of the tuple:
x = [0,1,2,3]x = True.(And of course, y is still 2.)
You've created a weird, weird thing there.
>>> y = 2
>>> range(4), y in range(4)
([0, 1, 2, 3], True)
The y in range(4) is a membership test.
The range(4), y in range(4) is a pair of items; a tuple.
The variable x is set to range(4), then the result of y in range(4).
The variable y is just laying around with a value; it is not set by the for statement.
This only works hacking around on the command line typing random stuff with y left laying around.
This isn't sensible Python code at all.
[And yes, the word in has two meanings. So do ()'s and several other pieces of syntax.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With