Winger Sendon Winger Sendon - 6 months ago 31
Python Question

Mysterious for loop in python

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:
if x==3:

Then execute
x in exp
, it returns True. What's happening here? I didn't assign anything to x. Did I? I am really confused.

**EDIT:**Sorry if I didn't say this before: x is not defined before.
Thank you everyone. I understand it now. the elements of
is assigned to x as exp is iterated over. And x in exp equals to True in the last line of code because the last element has been assigned to x.


Seems like you stumbled about in being somewhat overloaded in Python.

  • with x in exp, you are asking "Is x in exp?"
  • with for x in exp: ..., you tell Python "For each element in 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.