Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:
        print('True')

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.

Answer

Thank you everyone. I understand it now. the elements of exp is assigned to x as exp is iterated over. And x in exp equals True in the last line of code because the last element has been assigned to x.

like image 723
wingerse Avatar asked Aug 29 '14 17:08

wingerse


1 Answers

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.

like image 178
tobias_k Avatar answered Sep 16 '22 15:09

tobias_k