10 Python One-liners for Lambda Functions

Shen Ge
CodeX
Published in
5 min readJan 16, 2022

--

Python lambda function summarized in an example.

Background on Lambda Functions

Usually, a function in Python uses the def statement. Python also provides an expression form that generates function objects. However, it returns the function instead of assigning it to name. That’s why they are known as anonymous (unnamed) functions or lambda functions. The origin of the name comes from a similar tool in the Lisp language which originates from lambda calculus. You may find it intimidating but it’s really not! In Python, lambda just a keyword that introduces the expression syntactically.

lambda is an alternative way to code a function, without the need to have full statements, decorators, or annotations. Generally, lambda is very handy as a shorthand that allows you to embed a function definition within the code that uses it. Note that it’s entirely optional and you can always use def instead.

A key point is this: lambda is an expression, not a statement. Hence, it can appear in places a def is not allowed by Python syntax. For a def , a function can be referenced by name but must be created elsewhere. lambda returns a value that is a new function which can optionally be assigned a name. Here are 10 examples of how we can use lambda .

1. Set of all subsets

--

--

Shen Ge
CodeX

Engineer and console operator who helped America land back on the moon 2/22/2024. Enjoys code + poetry. Become a member: https://medium.com/@shenge86/membership