I've been having some trouble finding if an element is already stored in a list in a Python code. I've used two scripts. The second one I wrote turned out to work, but the first one didn't and I don't understand why (and it's bothering me). The list I have is called grains and looks like this :
[[a, b], [c, d], [e, f], ...].
Here is the first piece of code, not working :
for i in range(0, len(grains) - 1) :
if grains[i] == [x,y] :
return
else :
grains.append([x,y])
grains_restants = grains_restants - 1
fourmi_chargee = False
return
And here is the second piece of code, this one works :
if not([x,y] in grains) :
grains.append([x,y])
grains_restants = grains_restants - 1
fourmi_chargee = False
return
So I tried to understand why the first piece of code doesn't work, but I gave up. Do you know why ?
a,bingrains? what is the value ofxandy?range's parameters areinclusive, exclusive- that means it will include the first number you give it, and go all the way up to but not including, the second number. Hence, you never actually access the last element in your for loop.grains[0] == [x, y], and then theforloop willreturneither it'sTrueorFalse.[x,y]in your list. Instead, there should be[w, x]and['y, z].setinstead of alist