Skip to contentSkip to navigation

Module 07 · Lesson 01

Lambda Functions and Higher-Order Builtins

Pass functions as values: write small lambdas and use them with sorted, min, max, map and filter, then pair data with zip and test it with any and all.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Functions as values
  • Sort with key=
  • map, filter and zip
  • Watch a leaderboard sort

Functions you can pass around

A function is a value, like a number or a list. You can store it, hand it to another function and call it later.

  • lambda

    lambda n: n * 2 is a tiny function with no name and one expression.

  • key=

    sorted(), min() and max() take a key function that says what to compare.

  • map and filter

    map() changes every item. filter() keeps only the items that pass a test.

  • zip, any, all

    zip() pairs lists up. any() and all() answer yes or no about a whole list.

Passing functions everywhere

Whenever an app sorts, filters or picks the best of something, a small function is usually doing the choosing.

  • PlaylistsSort songs by length or by plays with one key= function.
  • Leaderboardsmax(players, key=...) finds the top scorer in one line.
  • Online shopsSort by price, keep only your size, and pair names with prices using zip().
  • Form checksall() makes sure every field is filled in before you press Send.

Sorting with a key

This line sorts players by their score. Tap each part to see its job.

Part 1 of 7

Tap any part of the code below, or press Next.1 of 7 explored

result:sorted() hands back a new list, stored under this name.

Pass functions around

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6A lambda

A lambda is a function in one line. Store it under a name and call it like any function.

Your turn: Write a lambda half that divides a number by 2, then print half(9).

Python
double = lambda n: n * 2
shout = lambda word: word.upper() + "!"
print(double(21))
print(shout("hello"))
Output
Press Run to see what it prints.

Watch a leaderboard sort

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. players = [("Ana", 82), ("Ben", 95), ("Cy", 77)]
  2. by_score = lambda p: p[1]
  3. ranked = sorted(players, key=by_score, reverse=True)
  4. best = ranked[0]
  5. names = list(map(lambda p: p[0], ranked))
  6. print(best[0], "wins with", best[1])
  7. print(names)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Numbers written as text: what prints?

print(sorted(["10", "9", "100"]))

0 of 6 answered

Common lambda misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Functions are values too

In Python a function is an object, just like a number or a list. The name you give it in def is a variable that refers to that object. Without parentheses you are talking about the function itself; with parentheses you are calling it.

Try it 1: edit me, then Run
def shout(text):
    return text.upper() + "!"

speak = shout          # no call: speak now refers to the same function
print(speak("hello"))  # HELLO!
Output
Press Run to see what it prints.

Because functions are values, you can put them in a list, return them from another function, or pass them as an argument. A function that takes another function as an argument is called a higher-order function. Several of Python's built-ins work this way.

lambda: a function in one expression

Sometimes the function you need is tiny and used only once. Writing a whole def for it feels heavy. A lambda creates a function inline:

Try it 2: edit me, then Run
double = lambda n: n * 2
print(double(4))       # 8
Output
Press Run to see what it prints.

The shape is lambda parameters: expression. There is no return keyword: the value of the expression is returned automatically. A lambda can take several parameters, separated by commas, or none at all. It can only hold one expression, so there are no loops, no assignments and no multi-line bodies. If you need any of those, write a normal def.

Assigning a lambda to a name, as above, is legal but unusual style. A lambda is most useful when you pass it straight into another function, where giving it a name would add nothing.

The key argument

sorted, min and max all accept a key argument. The key is a function that is called once for every item. Python then compares the results of that function instead of the items themselves.

Try it 3: edit me, then Run
words = ["banana", "kiwi", "apple"]
print(sorted(words))                  # ['apple', 'banana', 'kiwi']
print(sorted(words, key=len))         # ['kiwi', 'apple', 'banana']
print(max(words, key=len))            # banana
Output
Press Run to see what it prints.

Here key=len passes the built-in len function itself, without calling it. With lists of tuples or dictionaries, a lambda picks out the part to compare:

Try it 4: edit me, then Run
scores = [("Ana", 82), ("Ben", 95), ("Cy", 70)]
best = max(scores, key=lambda pair: pair[1])
print(best)                                        # ('Ben', 95)
print(sorted(scores, key=lambda pair: pair[1], reverse=True))
Output
Press Run to see what it prints.

The key only decides the order. The items that come out are the original items, unchanged. Python's sort is also stable: items with equal keys keep the order they had before, which is handy when you sort by one thing after another.

map and filter

map(function, items) calls the function on every item. filter(function, items) keeps only the items for which the function returns a true value.

Try it 5: edit me, then Run
prices = [4, 10, 25]
with_tax = list(map(lambda p: round(p * 1.2, 2), prices))
cheap = list(filter(lambda p: p < 20, prices))
print(with_tax)   # [4.8, 12.0, 30.0]
print(cheap)      # [4, 10]
Output
Press Run to see what it prints.

Both return a lazy iterator, not a list. It produces values one at a time when something asks for them, which is why the examples wrap them in list(). An iterator can be used only once; after a loop has gone through it, it is empty. The next lesson shows list comprehensions, which often say the same thing more clearly.

zip pairs things up

zip takes two or more sequences and walks them side by side, giving a tuple for each position:

Try it 6: edit me, then Run
names = ["Ana", "Ben", "Cy"]
ages = [31, 25, 40]
for name, age in zip(names, ages):
    print(name, age)
Output
Press Run to see what it prints.

zip stops at the end of the shortest input, silently dropping leftovers. Like map, it returns an iterator. dict(zip(keys, values)) is a quick way to build a dictionary from two lists.

any and all

any(items) is True if at least one item is true; all(items) is True only if every item is true. They pair well with map:

Try it 7: edit me, then Run
temps = [18, 22, 31]
print(any(map(lambda t: t > 30, temps)))   # True
print(all(map(lambda t: t > 15, temps)))   # True
Output
Press Run to see what it prints.

all([]) is True and any([]) is False, because an empty list has no item that breaks the rule and no item that meets it. Both stop as soon as they know the answer.

When to use what

Pass a named built-in like len or str.lower when one already does the job. Use a lambda for a short, obvious expression. When the logic needs a name to explain it, or more than one line, write a def and pass that name instead: sorted(orders, key=delivery_date) reads better than a clever lambda nobody can follow.

Syntax

The general shape of the statements in this lesson.

syntax.py
lambda x: x * 2                    # one-expression function
lambda a, b: a + b                 # several parameters
sorted(items, key=len)             # pass a function, do not call it
sorted(items, key=lambda x: x[1], reverse=True)
max(items, key=lambda x: x["score"])
list(map(func, items))             # apply func to every item
list(filter(func, items))          # keep items where func is true
zip(names, ages)                   # pairs, stops at the shortest
any(items) / all(items)
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Ranking a leaderboard

Beginner

A list of (player, points) tuples arrives unsorted. Print the players from highest to lowest points, with their rank, and name the player with the fewest points.

Python
players = [("Mia", 340), ("Leo", 515), ("Zoe", 290), ("Raj", 515)]

ranked = sorted(players, key=lambda p: p[1], reverse=True)
for rank, (name, points) in enumerate(ranked, start=1):
    print(f"{rank}. {name} {points}")

last = min(players, key=lambda p: p[1])
print("Needs practice:", last[0])
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The lambda tells sorted to compare the points, not the names. Leo and Raj tie on 515, and because the sort is stable they keep their original order. min uses the same kind of key to find the lowest score and returns the whole tuple, so last[0] is the name.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Calling the key function instead of passing it

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
words = ["pear", "fig"]
print(sorted(words, key=len()))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

TypeError: len() takes exactly one argument (0 given)

Write this instead

words = ["pear", "fig"]
print(sorted(words, key=len))

Why it happens

len() calls the function straight away with no argument. sorted needs the function itself so it can call it on each item.

In the real world

Where this shows up in software people use every day.

  1. Sorting products for a shop page

    Online retail

    A small online shop lets visitors sort products by price or by rating. The same product list is sorted with a different key depending on the button pressed.

    Why Python fits

    Each button only changes the key, so one product list serves every view. filter builds the budget view without touching the original list.

    Python
    products = [
        {"name": "Lamp", "price": 35.0, "rating": 4.2},
        {"name": "Mug", "price": 8.5, "rating": 4.8},
        {"name": "Rug", "price": 120.0, "rating": 3.9},
    ]
    
    by_price = sorted(products, key=lambda p: p["price"])
    print([p["name"] for p in by_price])
    
    top = max(products, key=lambda p: p["rating"])
    print("Best rated:", top["name"])
    in_budget = list(filter(lambda p: p["price"] <= 40, products))
    print(len(in_budget), "items under 40")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Is a lambda faster than a def?

No. Both create the same kind of function object. Choose by readability, not speed.

Can a lambda contain an if?

Only as a conditional expression, such as lambda n: 'even' if n % 2 == 0 else 'odd'. It cannot hold an if statement or a loop.

How do I sort by two things?

Return a tuple from the key, such as key=lambda p: (p['team'], p['name']). Tuples compare item by item, so the second value breaks ties in the first.

Does sorted change my original list?

No. sorted always builds a new list and leaves the original alone. The list method items.sort(key=...) takes the same key but changes the list in place and returns None.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.