Let exp = [1,2,3,4,5]
If I then execute x in exp
, it will give me False
. But if I execute :
for x in exp:
Seems like you stumbled about in
being somewhat overloaded in Python.
x
in exp
?"exp
, call it x
and do ..."The latter will assign each of the values in exp
to x
, one after the other, and execute the body of the loop with that value, so in the first iteration x
is assigned 1
, in the second 2
, and in the last 5
. Also, x
keeps this value after the loop!
Thus, before the loop, assuming that the variable x
is defined but has some other value, x in exp
will return False
, and after the loop, it returns True
, because x
is still assigned the last value from exp
.