That's how looping works in Python. 'For var in sequence
' will assign to var
as you iterate through the sequence.
If you were to simply print x
for example:
for x in [1, 2, 3, 4, 5]:
print x
You would see the following:
1
2
3
4
5
Perhaps what you were looking for was just the index of the value? If so, there are a couple of things you could do.
To iterate explicitly with the index, use enumerate(sequence)
as such:
for index, x in enumerate(mylist):
if index == 3:
do_stuff()
Where the first value (index
in this case) will always be the index of the current iteration.
You can also iterate over the length of the object using range(len(sequence))
which is sometimes useful if you're potentially modifying the list as you iterate. Here you're actually creating a separate list using range
, with length equal to the len
of the list. This will not assign from the list you're targeting -- rather it will assign from the list created by range()
-- so you'd have to access it using your for x in...
as the index of the list.
for x in range(len(mylist)):
if mylist[x] == 3:
things_and_stuff()
As for your second line and point of confusion - 'x in exp' - you will indeed see that x
remains assigned after the fact, and so using x in exp
will return True
because the last assigned value to x
is, in fact, in exp
.
>>> mylist = [1, 2, 3]
>>> for x in mylist:
... print x
...
1
2
3
>>> x
3
>>> x in mylist
True
x in exp
first, it will give you aNameError
, notFalse
. – Helminthiasisx
was bound to a value that wasn't inexp
before. You didn't tell us about the state ofx
before you ran thefor
loop however. – Paleolith