Mastering Anonymous Functions (Lambdas) in Python

Lesson Introduction

Welcome to our lesson on anonymous functions, also known as lambda functions, in Python. We'll explore what lambda functions are, how to create them, and when to use them. By the end, you'll understand the syntax and benefits of lambda functions, enabling you to write more concise and readable code.

Introduction to Lambda Functions

Lambda functions, or anonymous functions, are small, unnamed functions defined with the lambda keyword. They allow you to create simple functions concisely.

Lambda functions have the following syntax:

Python
lambda arguments: expression

The expression is evaluated and returned. Lambda functions can have any amount of arguments, but only one expression.

Lambda functions are useful when a small function is needed briefly. They offer:

  • Conciseness: Reduce verbosity by defining functions on the fly.
  • Readability: Improve readability in specific contexts.
  • Functional Programming: Support functional programming practices.

Basic Example

Let's start with a basic example to understand lambda functions. Suppose you need a function to print numbers:

Python
# Regular function to print a number
def print_number(n):
    print(n, end=' ')

# Lambda equivalent
print_number_lambda = lambda n: print(n, end=' ')

# Use the lambda function
numbers = [1, 2, 3, 4, 5]
for n in numbers:
    print_number_lambda(n)
print()  # 1 2 3 4 5

Here, lambda n: print(n, end=' ') is a lambda function that takes a single argument, n, and prints it. It's equivalent to defining a regular function, but more compact.

More Complex Lambda Expressions

Lambda functions can also handle multiple arguments and complex expressions. Consider needing to multiply numbers by a factor:

Python
multiply_by = lambda n, factor: n * factor

# Use the lambda function
numbers = [1, 2, 3, 4, 5]
for n in numbers:
    print(multiply_by(n, 2))
print()

Output:

2
4
6
8
10

Here, lambda n, factor: n * factor is a lambda function that takes n and factor and returns their product.

  • lambda n, factor: Defines the arguments.
  • n * factor: The expression that returns the product.

This example shows how lambda functions can simplify your code by allowing you to define small functions concisely.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal