Lambda functions

Intermediate Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

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

Lambda functions

  • lambda keyword
    • Represents an anonymous function

 

lambda arguments:
Intermediate Python for Developers

Lambda functions

  • lambda keyword
    • Represents an anonymous function

$$

lambda arguments: expression
  • Convention is to use x for a single argument
  • The expression is the equivalent of the function body
  • No return statement is required

$$

  • Can be stored as a variable
Intermediate Python for Developers

Creating a lambda function

# Lambda average function
print(lambda x: sum(x) / len(x))



<function <lambda> at 0x7f11ab813d80>
# Custom average function
def average(x):
    return sum(x) / len(x)  

print(average)
<function average at 0x7f11ab813ec0>
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])

$$

$$

# Print the average
print((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 print(average([3, 6, 9]))
6.0
Intermediate Python for Developers

Multiple parameters

# Lambda function with two arguments
power = lambda x, y: x**y


# Raise 2 to the power of 3 print(power(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
print(list(capitalize))
['John', 'Sally', 'Leah']
Intermediate Python for Developers

Custom vs. lambda functions

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

Let's practice!

Intermediate Python for Developers

Preparing Video For Download...