Just to briefly explain how this code works in your case:
When assigning first_number(2)
to second_num
on this line:
second_num = first_number(2)
you called the function first_number
and replaced n
with 2. The result is assigned to second_num
.
Now, the function first_number
doesn't just return a value like a constant: it returns a function, because lambda
is a function with no name (read further about how lambda works) and you just replaced n
with 2
and assigned that function to second_num
.
A function returning a function... kinda weird and cool at the same time don't you think? ;)
So you could say that this line:
second_num = first_number(2)
actually becomes (or you could at least interpret it this way):
def second_num(first):
return first * 2 #the 2 you passed in first_number
So after running second_num(20)
, it returns 40, obviously.
So what is lambda:
As told, lambda is an unnamed function, so a function with no name. You could interpret this line:
lambda first: first * n
as a function like:
def thisisafunction(first):
return first*n
So right after lambda
are the parameters, comma-separated. And after the colon :
is the body of the function.
Another way of applying lambda functions is to save some code. Like Python's filter
function (https://docs.python.org/3/library/functions.html#filter), which asks for a function as a parameter. It saves you quite some code this way:
numbers_list = [2, 6, 8, 10, 11, 4, 12, 7, 13, 17, 0, 3, 21]
filtered_list = list(filter(lambda num: (num > 7), numbers_list))
print(filtered_list)
vs
numbers_list = [2, 6, 8, 10, 11, 4, 12, 7, 13, 17, 0, 3, 21]
def filterfunction(num):
return num > 7
filtered_list = list(filter(filterfunction, numbers_list))
print(filtered_list)
Hopefully this makes things clear!