Skip to main content

Lambda Functions

Anonymous Functions in Python

· 2 min read

In the previous unit, we defined functions with def. Python has another way to create functions: the lambda keyword. Lambda functions are small, anonymous functions that you can define in a single line.

Lambda Functions

Lambda Syntax

A lambda function has this form:

lambda arguments: expression

The expression is evaluated and returned when you call the function. Here's a lambda that adds two numbers:

add = lambda x, y: x + y
result = add(5, 3)
print(result) # Outputs: 8

You can assign a lambda to a variable and call it like any other function.

When to Use Lambda Functions

Lambda functions shine when you need a quick, throwaway function. They're often used with functions like map(), filter(), and sorted().

Here's map() applying a lambda to every item in a list:

numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x ** 2, numbers)
print(list(squares)) # Outputs: [1, 4, 9, 16, 25]

The lambda takes each number and returns its square. map() applies this transformation to every element.

Lambda vs def

Lambda functions have limitations. They can only contain a single expression, not multiple statements. You can't include assignment, loops, or complex logic. And since they're anonymous, you can't reference them by name elsewhere in your code.

For anything beyond a simple one-liner, use def. Lambda functions are best for short operations where defining a full function would be overkill.

Project: Alternating Colors with Lambda

Let's use a lambda function to control the color of shapes. The lambda will decide the color based on whether the iteration number is even or odd.

import turtle

screen = turtle.Screen()
screen.bgcolor("white")

t = turtle.Turtle()

def draw_square(turtle, side_length):
for _ in range(4):
turtle.forward(side_length)
turtle.right(90)

get_color = lambda x: "red" if x % 2 == 0 else "blue"

for i in range(36):
t.color(get_color(i))
draw_square(t, 100)
t.right(10)

t.hideturtle()
turtle.done()

The lambda get_color returns "red" when x is even and "blue" when it's odd. The loop calls this function for each iteration, so the squares alternate between red and blue as the pattern spirals.

Try modifying the lambda to use different colors or add a third color for multiples of 3.

In the next unit, we'll make our Turtle graphics interactive by responding to keyboard and mouse events.