I learned python lambda functions from a codecademy.com tutorial – highly recommend.
My definition:
A one-liner for defining a function.
Example:
add_two = lambda x: x + 2
add_two(5) //prints 7
add_two(100) //prints 102
add_two(-2) //prints 0
Notes:
- Similar to defining a function with keyword def
- The variable after keyword lambda is your input
- Anything after the colon (:) is what you would be returning
- Whatever variable you’re assigning the lambda function is the name of the function
Adding if… else statements to our lambda functions:
Template:
<WHAT TO RETURN IF STATEMENT IS TRUE> if <IF STATEMENT> else <WHAT TO RETURN IF STATEMENT IS FALSE>
Example:
check_if_a_grade = lambda grade: "Got an A!" if grade >= 90 else "Did not get an A…"
Notes:
- Lambda functions only work as a one line command
- Helpful if you’re going to use the function only once
More Examples:
contains_a = lambda word: True if 'a' in word else False
print(contains_a("banana")) //True
print(contains_a("apple")) //True
print(contains_a("cherry")) //False
long_string = lambda str: True if len(str) > 12 else False
print(long_string("short")) //False
print(long_string("photosynthesis")) //True
ends_in_a = lambda str: True if str[-1] == 'a' else False
print(ends_in_a("data")) //True
print(ends_in_a("aardvark")) //False
even_or_odd = lambda num: 'even' if num % 2 == 0 else 'odd'
print(even_or_odd(10)) //even
print(even_or_odd(5)) //odd
ones_place = lambda num: num % 10
print(ones_place(123)) //3, because 3 is in the one's place of 123
print(ones_place(4)) //4