PythonSyntax and keywords
lambda
A short anonymous function written as a single expression.
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: expressionGood practices
#- For simple list transformations, a list comprehension is more readable than
mapwith a lambda. - When sorting by a field, you can also use
operator.itemgetter(1)instead of a lambda.
Related entries
#- lambda vs deflambda creates a short, anonymous function with one expression, while def defines a named function that can have multiple statements, default values, and a docstring.
- defDefines a function: a named block of code with parameters that you can call multiple times.
- sorted()Returns a new, sorted list built from the items of any collection.
- map()Calls a function for every item and returns an iterator of results.
- filter()Returns an iterator of items for which a function returns a truthy value.
Spotted a mistake or missing an example? Write to us.