Python Forum

Full Version: Why my lambda doesn't work properly?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I thought it should give 2 as passed argument is 1, so 1+1 should be done. But it gives me 1.

>>> def func(arg=lambda i: i+1):
print(arg)


>>> func(1)
1
I don't know why you'd expect anything else. You're setting the default value of the parameter arg to a lambda (why?), but when you call the function, you're passing the value 1, so the default isn't used.

What are you actually trying to achieve?
I tried to understand this part from Python tutorial about passing lambdas as an argument.

4.7.6. Lambda Expressions
...

The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:
>>>

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Remember that a lambda is a function. What do you do with functions? You call them of course. So the sort method calls the function passed as key on each pair to decide what to sort by (the second element in pair, pair[1]).

Perhaps it's useful to consider the function map that takes a list of values and a function to apply to each value, producing a new list. map exists in the standard library, so I'm calling my implementation below my_map:

>>> def my_map(f, values):
...     new_values = []
...     for v in values:
...             new_values.append(f(v))
...     return new_values
... 
>>> my_map(lambda v: v * 2, [1, 2, 3])
[2, 4, 6]
>>> my_map(lambda v: v.upper(), ["foo", "bar", "baz"])
['FOO', 'BAR', 'BAZ']
>>> 
my_map loops over each of the items in values, calling the function f on them (line 4) and putting those values in a new list which is returned. On line 7, I pass a lambda that just doubles its argument, so when my_map applies that to the items in [1, 2, 3], you get the list [2, 4, 6]. It's a similar thing with the second example on line 9.
Thank you very much, I got it now.
Another typical example is the function filter that keeps items for which a predicate function returns true. For example,

>>> my_filter(lambda v: v % 2 == 0, [1, 2, 3, 4, 5, 6])
[2, 4, 6]
>>> my_filter(lambda v: len(v) > 3, ["c++", "python", "c", "awk", "java"])
['python', 'java']
It is left as an exercise for you to implement my_filter ;).
Thanks, ndc85430.