Python Lambda Functions
Lambda functions (also called anonymous functions) are tiny functions that have no name and only have one expression as their body.
In Python they are defined using the lambda
keyword:
lambda <arguments> : <expression>
The body must be a single expression. Expression, not a statement.
This difference is important. An expression returns a value, a statement does not.
The simplest example of a lambda function is a function that doubles that value of a number:
lambda num : num * 2
Lambda functions can accept more arguments:
lambda a, b : a * b
Lambda functions cannot be invoked directly, but you can assign them to variables:
multiply = lambda a, b : a * b
print(multiply(2, 2)) # 4
The utility of lambda functions comes when combined with other Python functionality, for example in combination with map()
, filter()
and reduce()
.
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025