1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

Lambdas & sorting

A lambda is a tiny unnamed function written in one expression:

double = lambda x: x * 2

It shines as a key for sorted, min and max: "sort by this part of each item":

words = ["kiwi", "fig", "banana"]
sorted(words, key=lambda w: len(w))   # ['fig', 'kiwi', 'banana']

key receives each item and returns its comparison value. min and max accept the same keyword, but return the original item, not its key. For tuples like ("Ana", 31), index 0 is the name and index 1 is the age. Equal keys keep input order in sorted; min and max choose the first tied item.

A tuple key compares its first component, then its second to break ties. For example, (-score, name) puts higher scores first and names alphabetically within a score.

See it run

pets = ["tortoise", "cat", "owl", "hamster"]
by_len = sorted(pets, key=lambda p: len(p))
print(by_len)

The lambda is called once per item to get its sort key.

Practice lambdas & sorting

Exercise 1

  • Using the people list in the code editor below, set by_age to the people sorted youngest to oldest using a lambda key.
  • oldest = the name of the oldest person, using max with a key.

Exercise 2

Using the (name, distance) tuples in deliveries in the code editor below, sort by distance into by_distance using a lambda key. Keep equal-distance deliveries in their input order. Store the name of the nearest delivery in nearest using min with a lambda; choose the first delivery in a tie. Do not reorder deliveries itself. You may reuse one named lambda for both calls.

Exercise 3

Rank entries by score descending, breaking equal-score ties by name ascending. Store the ordered tuples in ranking using a lambda key, and the winning name in champion. Leave entries unchanged.

The explanation and tasks are public. Running this lesson requires an account with course access.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest