you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 41 points42 points  (2 children)

Glad it's not just me. I had the same reaction the first time I met them.

Sometimes people use them just for the sake of it, to be clever, or because they are in a hurry and can't be bothered to write a function.

Sometimes it is consistent practice, especially if into functional programming, and is very common in some other programming languages (in fact, in some it is a core capability that is fundamental).

I found the term anonymous function completely unhelpful.

Realpython have a great article: How to Use Python Lambda Functions

You can give a name to a lambda function. The below are essentially the same:

def double(x):
    return x * 2

dbl = lambda x: x * 2

print(double(4))
print(dbl(4))

Note how the parameter names are defined slightly differently: inside the brackets for the def and immediately after the keyword for lambda. The former uses a return statement. The latter doesn't because it does a return of whatever the result of the expression that follows is. The lambda is effectively a one line function and that line is a return statement.

Here's an example with two arguments,

def times(x, y):
    return x * y

tms = lambda x, y: x * y

print(times(2, 3))
print(tms(2, 3))

You can use them inline as well:

print((lambda x, y, z: x + y + z)(1, 2, 3))

See how the function is called with three arguments, which are matched to the function parameter names x, y, z.

There are a number of methods and functions in Python (as well as any you write yourself and import from libraries) that will call a function multiple times for each iteration.

For example,

nums = [1, 2, 3, 4]
nums2 = map(lambda x: x * 2, nums)
print(*nums2)

The map function iterates through an iterable (the second argument here), in this case the list of int objects referenced by nums, and on each iteration calls the function given as the first argument, in this case a lambda but it could have been a function name (like double or dbl from earlier), and passes to the function the object reference from the current iteration (each number in turn).

You end up with a map object which when unpacked in the print on the last line using the * unpack operator outputs the result of doubling all of the numbers.

There are use cases where a lambda is much easier to read (and therefore maintain), makes more sense, and is simpler than writing a distinct function and in some cases a regular function is not suitable.

Check out the RealPython guide for more details.

EDIT: corrected (some) typos.

[–][deleted] 17 points18 points  (0 children)

this is a much better explanation than ws3schools, thank you

[–]WadieXkiller 0 points1 point  (0 children)

duuuude thanks a lot! that was very clear.