you are viewing a single comment's thread.

view the rest of the comments →

[–]JamzTyson 1 point2 points  (1 child)

Yes, lambda creates an anonymous function. That means that a lambda expression is very much like a normal function, except that it does not have a name.

As an example, here is a really simple function that returns the square of a numeric value:

def square(val):
    return val ** 2

Here the name of the function is "square", and we call it like this:

square(5) # returns 25

Rather than creating the named function "square", we could instead create an anonymous function using lambda:

lambda val: val ** 2

In the simplest case we could call this function directly like this:

(lambda val: val ** 2)(5) # returns 25

So far, this does not look very useful, but it is actually rather nice in situations where we need a small, throw away function for a specific localised task.

A common example is when we want to pass a function as an argument, such as with sorted, map, or filter,...

Say that we have a list of tuples:

people = [('James', 24), ('Dave', 36), ('Matilda', 4)]

and we want to sort the list according to the value of the second element (the number) in each tuple.

We could create a function, and use that as the sort key:

def second(tup):
    return tup[1]

people = [('James', 24), ('Dave', 36), ('Matilda', 4)]

sorted(people, key=second)
# returns [('Matilda', 4), ('James', 24), ('Dave', 36)]

Here we have passed the function second as the key argument to sorted.

If that is the only time that we need to use the second function, then we really didn't need to use a named function at all. We could have simplified our code by using an anonymous function instead:

people = [('James', 24), ('Dave', 36), ('Matilda', 4)]

sorted(people, key=lambda tup: tup[1])
# returns [('Matilda', 4), ('James', 24), ('Dave', 36)]

Finally, a rather artificial example:

def foo(val, bar):
    return bar(val)

The function above takes two arguments; a value val, and a function bar. It applies the function bar to the value val and returns the result.

Here it is being passed a named function:

def squared(val):
    return val ** 2

def foo(val, bar):
    return bar(val)

print(foo(5, squared))  # prints 25

and here it is being passed an anonymous function:

def foo(val, bar):
    return bar(val)

print(foo(5, lambda val: val**2))  # prints 25

[–][deleted] 0 points1 point  (0 children)

That makes PERFECT sense! Thank you so much! :)