Winger Sendon - 9 months ago 50

Python Question

Let exp = [1,2,3,4,5]

If I then execute

`x in exp`

`for x in exp:`

if x==3:

print('True')

Then execute

`x in exp`

**EDIT:**Sorry if I didn't say this before: x is not defined before.

Thank you everyone. I understand it now. the elements of

`exp`

Answer

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`

.