0
0
Pythonprogramming~5 mins

Lambda with sorted() in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ASpecifies a function to extract a comparison key from each element.
BChanges the original list in place.
CReverses the list before sorting.
DFilters elements before sorting.
Which of these is a valid lambda function to sort a list of numbers in descending order using sorted()?
Asorted(numbers, key=lambda x: -x)
Bsorted(numbers, key=lambda x: x)
Csorted(numbers, reverse=False)
Dsorted(numbers, key=lambda x: x+1)
What will this code output? sorted(['apple', 'banana', 'cherry'], key=lambda x: x[0])
A['cherry', 'banana', 'apple']
B['banana', 'apple', 'cherry']
C['apple', 'cherry', 'banana']
D['apple', 'banana', 'cherry']
How can you sort a list of dictionaries by the value of the key 'age' using lambda?
Asorted(list_of_dicts, key=lambda d: age)
Bsorted(list_of_dicts, key=lambda d: d.age)
Csorted(list_of_dicts, key=lambda d: d['age'])
Dsorted(list_of_dicts, key=lambda d: d.get('name'))
What is the output of sorted([3, 1, 2], key=lambda x: x % 2)?
A[1, 2, 3]
B[2, 3, 1]
C[3, 1, 2]
D[1, 3, 2]
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.