← Previous Module 10: Advanced Functional Features Next →
Statement
Solution

Python Exercise 10.2: Lambda Sorting

Lambda functions are small, anonymous functions defined inline with the lambda keyword. They're especially useful as the key argument to sorted() or list.sort() when you need a custom sort order.

Your program should:

  • Start with a list of product tuples in the format (name, price): [("Laptop", 999), ("Mouse", 25), ("Monitor", 349), ("Keyboard", 79), ("Webcam", 59)]
  • Use sorted() with a lambda function as the key to sort by price in ascending order. Print the result.
  • Sort again by price in descending order using the reverse=True argument. Print the result.
  • Bonus: Sort alphabetically by product name and print the result.

Sample Interaction:

Input
Output
(None)
Sorted by price (low to high): ('Mouse', 25) ('Webcam', 59) ('Keyboard', 79) ('Monitor', 349) ('Laptop', 999) Sorted by price (high to low): ('Laptop', 999) ('Monitor', 349) ('Keyboard', 79) ('Webcam', 59) ('Mouse', 25) Sorted by name (A-Z): ('Keyboard', 79) ('Laptop', 999) ('Monitor', 349) ('Mouse', 25) ('Webcam', 59)

Solution

A lambda extracts the sort key from each tuple on the fly — no need to write a separate named function.

products = [ ("Laptop", 999), ("Mouse", 25), ("Monitor", 349), ("Keyboard", 79), ("Webcam", 59) ] # Sort by price ascending by_price_asc = sorted(products, key=lambda p: p[1]) print("Sorted by price (low to high):") for item in by_price_asc: print(item) # Sort by price descending by_price_desc = sorted(products, key=lambda p: p[1], reverse=True) print("\nSorted by price (high to low):") for item in by_price_desc: print(item) # Bonus: sort alphabetically by name by_name = sorted(products, key=lambda p: p[0]) print("\nSorted by name (A-Z):") for item in by_name: print(item)

Key Concepts:

  • lambda args: expression creates an anonymous single-expression function.
  • sorted(iterable, key=...) returns a new sorted list; the original is unchanged.
  • key=lambda p: p[1] tells Python to sort by the second element of each tuple (index 1 = price).
  • reverse=True flips the sort to descending without any extra logic.
  • Lambda functions are equivalent to a def function with a single return statement — just more concise.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top