The accepted answer from @citaret is fine but one aspect of this hasn't been made clear so far and that is - why is it we have a function in a function, why not just have f1(l, x)
?
The answer is that the function is likely used as an input to another function which takes exactly 1 argument and therefore we wish to 'capture' the list l
in the function so we need only supply x
when we invoke the function (this is referred to as a 'closure').
So for example we can create a function f
which takes a list l
as input and returns a new function (a closure) over l
which accepts x
and return True if x
is in l
:
f = lambda l: lambda x: x in l
We can then create a function f2
which is a closure over a list:
f2 = f([1, 2, 3])
Now we can map f2
to another list:
print map(f2, [2, 3, 4])
Produces:
[True, True, False]
Python's functools
module provides a partial function to help with this and perhaps make the intent of the inner lambda clearer, i.e. we could define f3
as:
f3 = functools.partial(lambda l, x: x in l, [1, 2, 3])
print map(f3, [2, 3, 4])
For a more comprehensive description of closures see this answer.