sorted() function in Python

In this lesson, you’ll learn how to sort a list using the Python sorted() method.

The sort() method sorts a list at its current location. To put it another way, it rearranges the components in the original list.

The sorted() function is used to return the new sorted list from the original list:

sorted(list)

The original list is not changed by the sorted() method.

Using the less-than operator (), the sorted() method sorts the members of the list from lowest to highest by default.

To reverse the sort order, set the reverse argument to True, as seen below:

sorted(list,reverse=True)

How to use Python sorted() function to sort a list of strings?

The sorted() function is used to sort a list of strings in alphabetical order in the following example:

guests = ['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer']
sorted_guests = sorted(guests)

print(guests)
print(sorted_guests)

Output

['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer']
['James', 'Jennifer', 'John', 'Mary', 'Patricia', 'Robert']

The original list does not change, as you can see from the output.
From the original list, the sorted() method returns a new sorted list.

The sorted() function is used in the following example to sort the guests list in reverse alphabetical order:

guests = ['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer']
sorted_guests = sorted(guests, reverse=True)

print(sorted_guests)

Output

['Robert', 'Patricia', 'Mary', 'John', 'Jennifer', 'James']