Josh Katofsky
Josh Katofsky

Reputation: 541

Check if object is in an iterable using "is" identity instead of "==" equality

if object in lst:
    #do something

As far as I can tell, when you execute this statement it is internally checking == between object and every element in lst, which will refer to the __eq__ methods of these two objects. This can have the implication of two distinct objects being "equal", which is usually desired if all of their attributes are the same.

However, is there a way to Pythonically achieve a predicate such as in where the underlying equality check is is - i.e. we're actually checking if the two references are to the same object?

Upvotes: 1

Views: 176

Answers (3)

Brian
Brian

Reputation: 1604

3list membership in python is dictated by the __contains__ dunder method. You can choose to overwrite this for a custom implementation if you want to use the normal "in" syntax:

class my_list(list):
    def __contains__(self, x):
        for y in self:
            if x is y:
                return True

        return False


4 in my_list([4, [3,2,1]])

>> True

[3,2,1] in my_list([4, [3,2,1]])  # Because while the lists are "==" equal, they have different pointers.

>>> False

Otherwise, I'd suggest kaya3's answer of using a generator check.

Upvotes: 1

William Bright
William Bright

Reputation: 535

if you want to specifically use is then just use filter like:

filtered_list = filter(lambda n: n is object, list)

Upvotes: 0

kaya3
kaya3

Reputation: 51093

Use the any function:

if any(x is object for x in lst):
    # ...

Upvotes: 0

Related Questions