Mar-11-2020, 04:42 AM
Mar-11-2020, 04:54 AM
I don't know why you'd expect anything else. You're setting the default value of the parameter
What are you actually trying to achieve?
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?
Mar-11-2020, 05:43 AM
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')]
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')]
Mar-11-2020, 06:36 AM
Remember that a lambda is a function. What do you do with functions? You call them of course. So the
Perhaps it's useful to consider the function
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.Mar-11-2020, 07:57 AM
Thank you very much, I got it now.
Mar-11-2020, 01:32 PM
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
;).Mar-29-2020, 04:26 PM
Thanks, ndc85430.