Lambda functions

Python intermedio per sviluppatori

Jasmin Ludolf

Senior Data Science Content Developer

Simple functions

def average(values):
    average_value = sum(values) / len(values)
    return average_value
Python intermedio per sviluppatori

Lambda functions

  • lambda keyword
    • Represents an anonymous function

 

lambda
Python intermedio per sviluppatori

Lambda functions

  • lambda keyword
    • Represents an anonymous function

 

lambda arguments
Python intermedio per sviluppatori

Lambda functions

  • lambda keyword
    • Represents an anonymous function

 

lambda arguments:
Python intermedio per sviluppatori

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
Python intermedio per sviluppatori

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>
Python intermedio per sviluppatori

Using lambda functions

# Get the average
(lambda x: sum(x) / len(x))
Python intermedio per sviluppatori

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
Python intermedio per sviluppatori

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
Python intermedio per sviluppatori

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
Python intermedio per sviluppatori

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']
Python intermedio per sviluppatori

Custom vs. lambda functions

Scenario Function Type
Complex task Custom
Same task several times Custom
Performed once Lambda
Simple task Lambda
Python intermedio per sviluppatori

Let's practice!

Python intermedio per sviluppatori

Preparing Video For Download...