34

Is there a way in python to call filter on a list where the filtering function has a number of arguments bound during the call. For example is there a way to do something like this:

>> def foo(a,b,c):
    return a < b and b < c

>> myList = (1,2,3,4,5,6)

>> filter(foo(a=1,c=4),myList)
>> (2,3)

This is to say is there a way to call foo such that a=1, c=4, and b gets bound to the values in myList?

3 Answers 3

70

One approach is to use lambda:

>>> def foo(a, b, c):
...     return a < b and b < c
... 
>>> myTuple = (1, 2, 3, 4, 5, 6)
>>> filter(lambda x: foo(1, x, 4), myTuple)
(2, 3)

Another is to use partial:

>>> from functools import partial
>>> filter(partial(foo, 1, c=4), myTuple)
(2, 3)
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for lambda. And also, if you want to use lambda without arguments, just use filter(lambda: foo(1,4), myTuple).
The lambda solution should be the chosen answer. It's a lot cleaner if you have to have the filter in a loop.
59

You can create a closure for this purpose:

def makefilter(a, c):
   def myfilter(x):
       return a < x < c
   return myfilter

filter14 = makefilter(1, 4)

myList = [1, 2, 3, 4, 5, 6]
filter(filter14, myList)
>>> [2, 3]

Comments

1
def foo(a,c):
    return lambda b : a < b and b < c

myList = (1,2,3,4,5,6)

g = filter(foo(1,4),myList)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.