Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python `in` keyword as a function used in a filter

Tags:

python

keyword

is it possible to use the python keyword in in a filter? I know that binary, unary, assignment operations are equivalent to a function call.

such as

''!=3

is the same as

''.__ne__(3)

is there an analogous thing for the in function? I want to do something like this. ..

filter( list1.__in__, list2 )

I guess this can be accomplished with writing the in function... but i just want to know if it is already built in or not.

like image 808
huan Avatar asked Jul 20 '11 17:07

huan


1 Answers

filter( list1.__contains__, list2 )

is more cleanly written as:

[ v for v in list2 if v in list1 ]

and to show equivalence:

>>> list1 = [2, 4, 6, 8, 10]
>>> list2 = [1, 2, 3, 4, 5]
>>> [ v for v in list2 if v in list1 ]
[2, 4]
like image 163
Dan D. Avatar answered Sep 27 '22 16:09

Dan D.