iTayb
iTayb

Reputation: 12743

Multiple parameters for the __contains__ function

Is it possible to pass the "__ contains __" function in a list more than one parameter? I'd like to check if at least one of the items i have in a list exist in a different list.

For example: [0,1,4,8,87,6,4,7,5,'a','f','er','fa','vz']

I'd like to check if the one of the items (8,5,'f') are on that list.

How can I do it?

Upvotes: 3

Views: 2685

Answers (3)

Alex
Alex

Reputation: 641

You may use sets:

list1 = [0,1,4,8,87,6,4,7,5,'a','f','er','fa','vz']
tuple1 = (8,5,'f')

def my_contains(first, second):
    return bool(set(first).intersection(second))

my_contains(list1, tuple1) # True
my_contains(list1, [1]) # True
my_contains(list1, (125,178,999)) # False

Upvotes: 2

kevpie
kevpie

Reputation: 26098

Use the builtin set type.

>>> l =  [0,1,4,8,87,6,4,7,5,'a','f','er','fa','vz']
>>> s = (8,5,'f')
>>> bool(set(s) & set(l))
True

Set methods will take iterables as arguments too, avoiding the creation of the set.

Most Concise:

2.6 provides set.isdisjoint(other) which likely is optimized to return as soon as a common element is found.

>>> not set(l).isdisjoint(s)
True

If you want to loop:

>>> any((val in s) for val in l)
True

Upvotes: 3

Rumple Stiltskin
Rumple Stiltskin

Reputation: 10405

AFAIK, __contains__ takes only one argument and it can't be changed.

However you can do following to get the desired result :

>>> a = [0,1,4,8,87,6,4,7,5,'a','f','er','fa','vz']
>>> any(map(lambda x: x in a, (8,5,'f')))
True

or

>>> from functools import partial
>>> from operator import contains
>>> f = partial(contains, a)
>>> any(map(f, (2,3)))
False

Upvotes: 7

Related Questions