lambda

A short anonymous function written as a single expression.

On this page

Example

#
Python
students = [("Emma", 92), ("Jack", 78), ("Mia", 85)]

by_score = sorted(students, key=lambda student: student[1], reverse=True)
print(by_score)

names = list(map(lambda s: s[0].upper(), students))
print(names)
Resultsaved result, you can check it
[('Emma', 92), ('Mia', 85), ('Jack', 78)]
['EMMA', 'JACK', 'MIA']

Definition and usage

#

A lambda expression creates a small function with no name: lambda x: x * 2. Only a single expression can follow the colon, and its result is returned. There is no room there for statements or multiple lines.

Lambdas are most often passed as an argument to other functions, for example as the sort key in sorted(), or as the function in map() and filter().

If a lambda starts getting long, or you are assigning it to a variable, it is better to define an ordinary function with def. It will have a name in error messages, and a docstring.

Syntax

#
Syntax
lambda params: expression

Good practices

#
  • For simple list transformations, a list comprehension is more readable than map with a lambda.
  • When sorting by a field, you can also use operator.itemgetter(1) instead of a lambda.

Related entries

#

Spotted a mistake or missing an example? Write to us.