Python sorted() function With Examples

Python sorted() function returns a sorted list from the items in the iterable.

Python sorted() function

Python sorted() function syntax is:

There are two optional arguments – key and reverse – which must be specified as keyword arguments.

  • iterable: elements from the iterable will be sorted. If key is not specified then natural sorting is used for the elements.
  • key: specifies a function of one argument that is used to extract a comparison key from each list element.
  • reverse: optional boolean argument. If specified as True then elements are sorted in reverse order.

Python sorted() string

String is iterable in Python, let’s see an example of using sorted() function with string argument.

Output: ['c', 'd', 'e', 'g', 'i', 'j', 'm', 'n']

Python sorted() reverse

Let’s see the sorted list when reversed is passed as True.

Output: ['z', 'y', 'x', 'b', 'a']

Python sorted() tuple

Output:

Python sorted() key

Let’s say we want to sort a sequence of numbers based on their absolute value, we don’t care about their being positive or negative. We can achieve this by passing key=abs to sorted() function. Note that abs() is the built-in function that returns the absolute value of the number.

Output: [1, -1, 2, -2, 3]

Python sort list

Let’s see some examples of using sorted() function with list.

Output:

sorted() vs list.sort()

  • sorted() function is more versatile because it works with any iterable argument.
  • Python sorted() function builds a new sorted list from an iterable whereas list.sort() modifies the list in-place.

sorted() with iterable of different element types

Let’s see what happens when we try to use sorted() function with iterable having different element types.

Output:

sorted() with custom objects

We can use sorted() function to sort a sequence of custom object based on different types of criteria.

Let’s say we have an Employee class defined as:

Now we have a list of employee objects as:

Sort list of employees based on id

Output:

Sort list of employees based on age

Output:

Summary

Python sorted() function is guaranteed to be stable. It’s very powerful and allows us to sort a sequence of elements based on different keys.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: