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)Code language: Python (python)

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)Code language: Python (python)

Python sorted() function examples

Let’s take some examples of using the Python sorted() function.

1) Using Python sorted() function to sort 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)Code language: Python (python)

Output:

['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer']
['James', 'Jennifer', 'John', 'Mary', 'Patricia', 'Robert']Code language: Python (python)

As you can see clearly in the output, 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)Code language: Python (python)

Output:

['Robert', 'Patricia', 'Mary', 'John', 'Jennifer', 'James']Code language: Python (python)

2) Using Python sorted() function to sort 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)Code language: Python (python)

Output:

[4, 5, 6, 7, 8, 9]Code language: Python (python)

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)Code language: Python (python)

Output:

[9, 8, 7, 6, 5, 4]Code language: Python (python)

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.
Did you find this tutorial helpful ?