Lambda functions in Python

/python/basics/docstring/

Introduction

Lambda functions are named after the lambda calculus, with

In modern programming languages lambda functions

In Python lambdas are anonymous callable objects. Using lambdas is often useful, but doing it has to be

Example

>>> (lambda x: x + 1)(2)

3

How it works:

(lambda x: x + 1)(2) = lambda 2: 2 + 1 = 2 + 1 = 3

>>> add_one = lambda x: x + 1
>>> add_one(2)

3

An example of using a lambda to build a sort key sorted() .

scientists = [ 'Marie Curie', 'Dmitri Mendeleev', 'Nikolay Basov', 'Alexander Popov', 'Igor Kurchatov', 'Niels Bohr', 'Oliver Heaviside','Max Planck', 'Isaac Newton', 'Rosalind Franklin' ] # The name from the string is turned into a list # the last element is taken from the list # which is used as the key print(sorted(scientists, key=lambda name: name.split()[-1])) # A lambda is an expression that returns # a callable object (callable object) last_name = lambda name: name.split()[-1] print(last_name) print(last_name("Nikola Tesla")) # Without a lambda # the functions that extract the name # and the surname look like this: def last_name(name): return name.split()[-1] def first_name(name): return name.split()[0] print(l_name("Nikola Tesla")) print(first_name("Nikola Tesla"))

['Nikolay Basov', 'Niels Bohr', 'Marie Curie', 'Rosalind Franklin', 'Oliver Heaviside', 'Igor Kurchatov', 'Dmitri Mendeleev', 'Isaac Newton', 'Max Planck', 'Alexander Popov'] <function <lambda> at 0x7f2ccf9c3af0> Tesla Tesla Nikola

Differences from ordinary functions

Functions Lambdas
def name(args): body lambda args: expr
A statement, that defines An expression, that is evaluated
Must have a name Has no name
The arguments are in parentheses and listed A list of arguments separated by commas ends
Zero or more arguments are supported. Zero arguments means empty brackets Zero or more arguments are supported. Zero arguments means a colon right after lambda (lambda
The body of a function is a block (with proper indentation) of statements The body of a lambda is a single expression
For a function to return something other than None you have to The return value is determined by the expression containing You cannot use the return statement.
Can have docstring Cannot have docstring
Easy to test Hard to test because they cannot be called by name
Banner image

Examples of use

Article author: Andrei Olegovich

Banner image