Reputation: 541
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
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
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