tomfl
tomfl

Reputation: 707

Searching for an element in a list with a loop in Python

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 ?

Upvotes: 1

Views: 11637

Answers (2)

shizhz
shizhz

Reputation: 12531

Your first piece of code will not loop list grains as your expectation, it'll actually only compare grains[0] == [x, y] and the for loop will exit due to you have return in either if and else branch, while the second implementation will check whether [x, y] is in the whole list grains or not.

You should NOT use code like this but the for loop code is supposed to be:

for i in grains:
    if i == [x,y] :
        break
else:
    grains.append([x,y])
    grains_restants = grains_restants - 1
    fourmi_chargee = False

Upvotes: 2

masnun
masnun

Reputation: 11916

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

You are matching every element in the list against [x,y] but you really want to check if [x,y] exists already. That's what the 2nd code snippet does using the in operator.

Now why does the first one not work? You didn't mention what errors / unexpected scenarios you were getting but I can see one. Let's assume that the [x,y] element is in index 3 (4th item). But you're comparing it to 0,1,2 => all of them won't match and add a duplicate item and then return. That's really not what you want.

To check if the element exists, using the in operator is the best idea. You could also use list.count to see if any element exists in the list (and how many times it appears in that list).

Upvotes: 1

Related Questions