Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: for statement behavior

Tags:

python

syntax

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.

like image 345
BandGap Avatar asked Aug 12 '26 23:08

BandGap


2 Answers

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:

  1. x = [0,1,2,3]
  2. x = True.

(And of course, y is still 2.)

like image 164
Amber Avatar answered Aug 14 '26 12:08

Amber


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.]

like image 28
S.Lott Avatar answered Aug 14 '26 13:08

S.Lott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!