Lambda
lamba x: x , list
Means that every member of list will be run through the function , whatever we say is. If we say is **2 every member of list will be squared. If we say is /4 then every member of list will be divided by 4.
And Friends: filter(), map(), reduce()
filter()
filter(lambda x : x % 3 == 0, list)
Will filter list, leaving behind every member divisible by 3
map()
map(lambda x: x * 2 + 10. list)
Returns a list where every member is that member of list multiplied by 2 and increased by 10
reduce()
Creates a chain reaction, pairwise between the first two elements of list, and then the next, and then the next, until there is no more “and then next”s (so, n-1 times for a list of length n)
Going Bigger (*args and **kwargs)
args and kwargs aren’t real. * and ** are the symbols that actually clue python into what you are trying to do. * is a wildcard in UNIX too, so if it seems familiar, it may well be.
*args (or *bunnies or *yaks or *bananas)
Lets Python know that you are feeding your function a list of arguments and the length of that list is not fixed.
**kwargs (or **hares or **buffalo or **plantains)
Lets Python know you are going to be feeding it named arguments of inconsistent number. When your function accesses these arguments it has already cast them into a variable name, so if one of your keywords is firstname, and another is address, when you as for address you get the latter and everything is all linked up.
all together now
If your function is going to be fed a combination of these, the proper order of things is
def f(one_arg, *args, **kwargs):
These are my crib notes from the following pages, which are super-clear and deserve a closer reading if you have not already.
Thanks for the excellent post on Python lambdas!
LikeLike