lettura simple

Python's sorted() Function

Python boasts a rich set of built-in functions, and among the most versatile is the sorted() function. Designed to sort elements from any iterable (think lists, sets, and more), it returns a freshly sorted list. Let's break down its syntax:

sorted(iterable, *, key=None, reverse=False)

Here's what each parameter does:

  • iterable: The collection you're aiming to sort, be it a list, tuple, or set.
  • key (optional): A custom function to determine the sort order. It's applied to each item in the iterable.
  • reverse (optional): A simple boolean. When set to True, it flips the sort order to descending.

The function returns a new list with the sorted items.

One key thing to note: sorted() produces a new list, leaving the original untouched. If in-place sorting is your goal, you might want to turn to the list.sort() method. But remember, while sort() is exclusive to lists, sorted() plays well with any iterable.

Practical Examples to Get You Started

Sorting numbers? Here's a simple example.

Create a list with some numeric values:

numbers = [34, 1, 78, 5]

Then, sort the list using the sorted() function.

sorted(numbers)

The result is a new list with the items sorted in ascending order.

[1, 5, 34, 78]

To get the items in descending order, use the reverse argument.

sorted(numbers, reverse=True)

This will give you:

[78, 34, 5, 1]

Sorting strings? sorted() naturally arranges words in alphabetical order.

words = ["apple", "banana", "cherry"]

Then, sort the list using sorted()

sorted(words)

The function will return the strings in alphabetical order.

['apple', 'banana', 'cherry']

The key parameter unlocks more advanced sorting.

Consider a list of plane coordinates (x,y)

points = [(1, 1), (3, 4), (0, 2)]

To sort these points by their distance from the origin:

sorted(points, key=lambda p: p[0]**2 + p[1]**2)

The sorted() function uses the anonymous function to sum the (x,y) coordinates and then sorts the results in ascending order.

[(1, 1), (0, 2), (3, 4)]

And if you're working with dictionaries, you can sort them based on their values.

For instance, create a dictionary:

dictionary = {'a': 5, 'b': 1, 'c': 8}

Then, sort the dictionary by its values in ascending order.

sorted(dizionario.items(), key=lambda x: x[1])

Python will return the sorted dictionary.

[('b', 1), ('a', 5), ('c', 8)]

In conclusion, Python's sorted() function is a powerful tool in any developer's arsenal. Whether you're a novice or a seasoned pro, mastering it will undoubtedly streamline your coding endeavors.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin