Python sorted

Summary: in this tutorial, you’ll learn how to use the Python sorted() function to sort a list.

Introduction to the Python sorted() function #

The sort() method sorts a list in place. In other words, it changes the order of elements in the original list.

To return the new sorted list from the original list, you use the sorted() function:

sorted(list)

The sorted() function doesn’t modify the original list.

By default, the sorted() function sorts the elements of the list from lowest to highest using the less-than operator (<).

If you want to reverse the sort order, you pass the reverse argument as True like this:

sorted(list,reverse=True)

Sorting a list of strings #

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

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

print(guests)
print(sorted_guests)

Try it

Output:

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

The output indicates the original list doesn’t change. The sorted() method returns a new sorted list from the original list.

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

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

print(sorted_guests)

Try it

Output:

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

Sorting a list of numbers #

The following example uses the sorted() function to sort a list of numbers from smallest to largest:

scores = [5, 7, 4, 6, 9, 8]
sorted_scores = sorted(scores)

print(sorted_scores)

Try it

Output:

[4, 5, 6, 7, 8, 9]

The following example uses the sorted() function with the reverse argument sets to True. It sorts a list of numbers from largest to smallest:

scores = [5, 7, 4, 6, 9, 8]
sorted_scores = sorted(scores, reverse=True)

print(sorted_scores)

Try it

Output:

[9, 8, 7, 6, 5, 4]

Summary #

  • Use the sorted() function to return a new sorted list from a list.
  • Use the sorted() function with the reverse argument sets to True to sort a list in the reverse sort order.

Quiz #

Quiz

Python sorted() Function

10 questions

To help you understand how to use the Python sorted() function to sort lists effectively.

Was this helpful?