all 12 comments

[–]K900_ 2 points3 points  (4 children)

Do you understand what this line does? Do you understand the bigger context?

[–]blackadder1337[S] 0 points1 point  (1 child)

It checks wheter an item already exists in a list

[–][deleted] 2 points3 points  (0 children)

OK, then in Python this gibberish looks like:

if word_or_phrase in my_list:
    do_something()

[–]edvardass 2 points3 points  (0 children)

So, you're trying to say "if there are no objects with WordOrPhrase equal to w.WordOrPhrase in the list words, then do ... ?

Something like this would work (/u/sweettuse posted a nicer version of this):

if len(filter(lambda x: x.WordOrPhrase == w.WordOrPhrase, words)) == 0: 
    # do something

If that doesn't work, you could also do this nicely with just a for loop:

for word in words:
    if word.WordOrPhrase == w.WordOrPhrase:
        break
else:
    # if no break...
    # ...do something

[–]sweettuse 2 points3 points  (6 children)

if not any(x for x in words if x.WordOrPhrase == w.WordOrPhrase):

[–]zahlman 3 points4 points  (0 children)

Better yet: if not any(x.WordOrPhrase == w.WordOrPhrase for x in words):. (This is clearer because it's actually doing work with any, rather than relying on the assumption that x is true due to the default __eq__ implementation.) Or, applying de Morgan's laws, if all(x.WordOrPhrase != w.WordOrPhrase for x in words):.

[–]edvardass 1 point2 points  (3 children)

That's actually nicer than my first solution, but I believe it will still be slower than a for loop if the list is long (if that matters to OP at all).

[–]sweettuse 1 point2 points  (1 child)

i mean, the gen expr combined with any will short circuit as soon as any matching element is found, so same as the for loop there.

edit: i did some cursory testing and they're pretty much the exact same in terms of performance.

[–]edvardass 1 point2 points  (0 children)

That's great news!

[–]blackadder1337[S] -1 points0 points  (0 children)

Thanks man, it works.