Lambda functions

Intermediate Python for Developers

George Boorman

Curriculum Manager, DataCamp

Simple functions

def average(values):
    average_value = sum(values) / len(values)
    return average_value
Intermediate Python for Developers

Lambda functions

  • lambda keyword
    • Represents an anonymous function

 

lambda
Intermediate Python for Developers

Lambda functions

  • lambda keyword
    • Represents an anonymous function

 

lambda argument(s)
Intermediate Python for Developers

Lambda functions

  • lambda keyword
    • Represents an anonymous function

 

lambda argument(s):
Intermediate Python for Developers

Lambda functions

  • lambda keyword
    • Represents an anonymous function
    • Can store as a variable and call it
lambda argument(s): expression
  • Convention is to use x for a single argument
  • The expression is the equivalent of the function body
  • No return statement is required
Intermediate Python for Developers

Creating a lambda function

# 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)>
Intermediate Python for Developers

Using lambda functions

# Get the average
(lambda x: sum(x) / len(x))
Intermediate Python for Developers

Using lambda functions

# Get the average
(lambda x: sum(x) / len(x))([3, 6, 9])
6.0
Intermediate Python for Developers

Storing and calling a lambda function

# Store lambda function as a variable
average = lambda x: sum(x) / len(x)

# Call the average function average([3, 6, 9])
6.0
Intermediate Python for Developers

Multiple parameters

# Lambda function with two arguments
(lambda x, y: x**y)(2, 3)
8
Intermediate Python for Developers

Lambda functions with iterables

  • map() applies a function to all elements in an iterable
names = ["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']
Intermediate Python for Developers

Custom vs. lambda functions

Scenario Function Type
Complex task Custom
Same task several times Custom
Simple task Lambda
Performed once Lambda
Intermediate Python for Developers

Let's practice!

Intermediate Python for Developers

Preparing Video For Download...