Intermediate Python for Developers
George Boorman
Curriculum Manager, DataCamp
def average(values):
average_value = sum(values) / len(values)
return average_value
lambda
keyword
lambda
lambda
keyword
lambda argument(s)
lambda
keyword
lambda argument(s):
lambda
keywordlambda argument(s): expression
x
for a single argumentexpression
is the equivalent of the function bodyreturn
statement is required# Lambda average function
lambda x: sum(x) / len(x)
<function __main__.<lambda>(x)>
# Custom average function
def average(x):
return sum(x) / len(x)
average
<function __main__.average(x)>
# Get the average
(lambda x: sum(x) / len(x))
# Get the average
(lambda x: sum(x) / len(x))([3, 6, 9])
6.0
# Store lambda function as a variable average = lambda x: sum(x) / len(x)
# Call the average function average([3, 6, 9])
6.0
# Lambda function with two arguments
(lambda x, y: x**y)(2, 3)
8
map()
applies a function to all elements in an iterablenames = ["john", "sally", "leah"]
# Apply a lambda function inside map() capitalize = map(lambda x: x.capitalize(), names)
print(capitalize)
<map object at 0x7fb200529c10>
# Convert to a list
list(capitalize)
['John', 'Sally', 'Leah']
Scenario | Function Type |
---|---|
Complex task | Custom |
Same task several times | Custom |
Simple task | Lambda |
Performed once | Lambda |
Intermediate Python for Developers