Python value not in list of objects

I want to check if a given value exists in a list of objects (stack). Each object contains an attribute (state) that I want to check against.

Sample list:

[<state.State instance at 0x02A64580>, <state.State instance at 0x02A646E8>, <state.State instance at 0x02A649B8>]

What I have tried, doesn't seem to do it:

for neighbor in neighbors:
        if neighbor.state != any(s.state for s in stack):

How can I achieve that?


any() returns a bool that is true if any of the elements is true. It's basically a chained or. I think what you might want is something like the following:

for neighbor in neighbors:
    present = False
    for s in stack:
        if neighbor.state == s.state:
            present = True
    if not present:

Alternatively, you might want to use some kind of ordered set, like this one: . (Disclaimer: I did not test this package.)

# setup
class MyObj(object):
    def __init__(self, state):
        self.state = state

states = range(10)
objs = [MyObj(s) for s in states]

neighbor_states = [1,22,5,40,90]
neighbors = [MyObj(s) for s in neighbor_states]

# algorithm
for neighbor in neighbors:
    if neighbor.state not in (o.state for o in objs):

# testing      
for o in objs:
    print o.state


 ? Is this if statement well expressed?
 ? How do I test one variable against multiple values?
 ? concatenating multi-indexed information within a pandas dataframe
 ? How can I change a specific row label in a Pandas dataframe?
 ? Fabric command not working with specific ssh key
 ? How to run Python Scripts on Mac Terminal using Docker with Tensorflow?
 ? Images download with BeautifulSoup
 ? Passing a list of values from Python to the IN clause of an SQL query
 ? How to plot all files in one folder in python?
 ? how to speed up the computation?