Skip to content

๐Ÿงฉ Python Lambda Functions Guide

Beginner-friendly documentation about Python lambda functions, anonymous functions, and common functional programming patterns.

This document explains: - what lambda functions are - lambda syntax - common use cases - map() - filter() - sorted() - practical examples - common mistakes


๐Ÿ“š Table of Contents


๐Ÿ“– What is a Lambda Function?

A lambda function is: - a small anonymous function - created in a single line - often used for quick operations

Unlike normal functions: - lambda functions usually do not have names


๐Ÿงฑ Basic Syntax

lambda arguments: expression

Simple Example

square = lambda x: x * x

print(square(5))

Output:

25

Equivalent Normal Function

def square(x):
    return x * x

Both functions behave the same way.


โš™๏ธ Lambda vs Normal Functions

Lambda Function

lambda x: x + 1

Normal Function

def add_one(x):
    return x + 1

๐Ÿ“ฆ Returning Values

Lambda functions automatically return the expression result.


๐Ÿ”— Using Multiple Arguments

add = lambda a, b, c: a + b + c

๐Ÿ—‚๏ธ Lambda with sorted()

players.sort(key=lambda player: player[1])

๐Ÿงช Lambda with map()

numbers = [1, 2, 3]

result = list(map(lambda x: x * 2, numbers))

๐Ÿ” Lambda with filter()

numbers = [1, 2, 3, 4]

evens = list(filter(lambda x: x % 2 == 0, numbers))

๐ŸŽฎ Real 42 Examples

Sorting Coordinates

positions.sort(key=lambda pos: pos[0])

Filtering Valid Zones

valid_zones = list(filter(lambda zone: zone.active, zones))

โš ๏ธ Common Beginner Mistakes

โŒ Trying to Use Multiple Lines

Wrong:

lambda x:
    x + 1

Lambda functions must stay on ONE line.


โŒ Forgetting list()

map() and filter() return iterators.

Usually convert them:

list(map(...))

๐Ÿ“š Best Practices

  • Use lambdas for short operations
  • Prefer normal functions for complex logic
  • Keep lambdas readable
  • Avoid nested lambdas

๐Ÿ“š Final Notes

Lambda functions are extremely common in modern Python.

They are especially useful for: - quick transformations - sorting - filtering - concise operations