🎓 A1Learner
🔍
0 of 116 lessons completed

Python Lambda Functions

A lambda is a tiny one-line function with no name. A lambda holds one expression.

A tiny job with def

A named def takes three lines for this tiny job.

def double(n):
    return n * 2

print(double(6))

A lambda in one line

This lambda doubles a number. We save it in a variable so we can call it.

double = lambda n: n * 2
print(double(6))

A lambda with two arguments

Arguments come before the colon. The part after the colon is the result.

add = lambda a, b: a + b
print(add(3, 4))

Sort with a key

Plain sorted() puts words in alphabet order. A key lambda can sort by length instead.

words = ["banana", "kiwi", "fig"]
print(sorted(words))
print(sorted(words, key=lambda word: len(word)))

Sort by the last letter

name[-1] is the last letter of a name. The lambda hands that letter to sorted().

names = ["Kim", "Ada", "Leo", "Sue"]
print(sorted(names, key=lambda name: name[-1]))

Example

names = ["Zoe", "Adam", "Lily", "Ben"]
words = ["banana", "fig", "kiwi", "plum"]

by_last = sorted(names, key=lambda name: name[-1])
by_length = sorted(words, key=lambda word: len(word))

print(by_last)
print(by_length)

Key points

  • lambda: a tiny one-line function with no name
  • Anonymous: without a name.
  • A lambda is an anonymous function.
  • Use lambda to write a small function in one line: lambda arguments: result
  • A lambda holds one expression.
  • An expression is a piece of code that gives a value.
  • key=: the rule sorted() uses to order each item

In this example, names holds four names and words holds four words. The first sorted() call uses a lambda that returns the last letter of each name. So Zoe with e comes first, then Adam, Ben and Lily. The second sorted() call uses a lambda that returns the length of each word. fig is shortest, and banana is longest. The two print lines show both new lists.

Note

A lambda cannot hold several steps.

Use def when the job needs more than one line.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which lambda adds 5 to a number?