Introduction
You use lambda with sorted() to quickly tell Python how to sort things without writing a full function.
Jump into concepts and practice - no test required
sorted(iterable, key=lambda item: expression)
sorted([5, 2, 9, 1], key=lambda x: x)
sorted(['apple', 'banana', 'pear'], key=lambda x: len(x))
sorted([{'name': 'Bob', 'age': 25}, {'name': 'Ann', 'age': 20}], key=lambda x: x['age'])
fruits = ['apple', 'banana', 'pear', 'kiwi'] sorted_fruits = sorted(fruits, key=lambda x: len(x)) print(sorted_fruits)
key argument do when used with sorted() and a lambda function in Python?key in sorted()key argument takes a function that extracts a value from each item to use for sorting.lambda works with keylambda function defines this extraction rule inline, telling sorted() what to compare.sorted() how to compare items by extracting a value from each item. -> Option Ckey=lambda x: value means compare by value [OK]data = [(2, 'b'), (1, 'a'), (3, 'c')] by the first element using sorted() and a lambda?key argumentkey argument must be named and assigned a function, here a lambda.lambda x: x[0] correctly extracts the first element of each tuple for sorting.data = ['apple', 'banana', 'cherry'] sorted_list = sorted(data, key=lambda x: len(x)) print(sorted_list)
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
sorted_data = sorted(data, key=lambda x: x['age'])
print(sorted_data)products = [('pen', 1.5), ('notebook', 2.0), ('eraser', 0.5), ('pencil', 1.5)]How would you sort this list first by price ascending, then by product name alphabetically using sorted() and lambda?lambda x: (x[1], x[0]) returns price first, then product name.