Recall & Review
beginner
What does the
sorted() function do in Python?It returns a new list containing all items from the iterable in ascending order by default.
Click to reveal answer
beginner
What is a lambda function in Python?
A lambda function is a small anonymous function defined with the
lambda keyword, which can take any number of arguments but has only one expression.Click to reveal answer
intermediate
How do you use a lambda function with
sorted()?You pass the lambda function to the
key parameter of sorted() to specify the value to sort by for each item.Click to reveal answer
intermediate
Example: Sort a list of tuples by the second item using
sorted() and lambda.sorted_list = sorted([(1, 3), (2, 1), (3, 2)], key=lambda x: x[1]) # Result: [(2, 1), (3, 2), (1, 3)]
Click to reveal answer
intermediate
How to sort a list of strings by their length using
sorted() and lambda?Use
sorted(strings, key=lambda s: len(s)) to sort strings by length from shortest to longest.Click to reveal answer
What does the
key parameter in sorted() do?✗ Incorrect
The
key parameter takes a function that returns a value used to compare elements during sorting.Which of these is a valid lambda function to sort a list of numbers in descending order using
sorted()?✗ Incorrect
Using
key=lambda x: -x sorts numbers by their negative value, effectively sorting descending.What will this code output?
sorted(['apple', 'banana', 'cherry'], key=lambda x: x[0])✗ Incorrect
Sorting by the first letter keeps the list in the same order because 'a' < 'b' < 'c'.
How can you sort a list of dictionaries by the value of the key 'age' using lambda?
✗ Incorrect
Use
lambda d: d['age'] to access the 'age' value in each dictionary for sorting.What is the output of
sorted([3, 1, 2], key=lambda x: x % 2)?✗ Incorrect
Sorting by
x % 2 groups even numbers (0) before odd numbers (1), so 2 comes before 3 and 1.Explain how to use a lambda function with
sorted() to sort a list of complex items.Think about how to tell Python what part of each item to sort by.
You got /4 concepts.
Describe a real-life example where sorting with a lambda function would be useful.
Consider sorting a list of people by age or sorting products by price.
You got /3 concepts.