single
Sorted Fundamentals
Swipe to show menu
Sorting data is a common operation when working with lists in Python. The sorted function is a built-in higher-order function that allows you to sort any iterable and returns a new sorted list, leaving the original data unchanged. You can use sorted with or without custom sorting logic. By default, sorted arranges elements in ascending order, but you can control the sort order and criteria using its optional parameters.
The most important parameters for sorted are:
iterable: the data you want to sort;key: an optional function that determines the value to sort by for each element;reverse: a Boolean value that, if set toTrue, sorts the data in descending order.
Suppose you have a list of numbers and want to sort them in ascending order. You can simply call sorted(numbers). If you want to sort the numbers in descending order, you can pass reverse=True.
12345numbers = [9, 5, 2, 1] # Sorting in reverse order sorted_desc = sorted(numbers, reverse=True) print(sorted_desc)
You can also use the key parameter to sort more complex data structures, such as lists of tuples or dictionaries, by specifying a function that extracts the comparison value from each element.
12345words = ["apple", "kiwi", "banana"] # Sorting by the length of each string sorted_words = sorted(words, key=len) print(sorted_words)
You can pass any function to the key parameter, including a lambda function or a previously defined function. This makes sorted a higher-order function, as it accepts another function as an argument. Sorting is not limited to numbers or strings; you can sort complex objects as long as you provide a suitable key function.
The original iterable is not changed by sorted, it always returns a new list. If you want to sort a list in place, use the list.sort() method instead.
Swipe to start coding
Sort a list of tuples by the second element in each tuple using the sorted function and a named function as the key parameter.
- You are given a list named
pairscontaining tuples of two integers. - Define a function named
get_second_elementthat takes a tuple and returns its second value. - Use the
sortedfunction and passget_second_elementas thekeyparameter to sortpairsby the second value in each tuple. - Store the result in a variable named
sorted_pairs. - Do not forget to remove
pass.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat