CodeBlanks Logo Icon CodeBlanks

Sorting lists

Learn sorting with sort() and sorted().

Sorting lists

There are two ways to sort a list: sort sorts the list in place, sorted returns a new sorted list:

numbers = [3, 1, 2]
numbers.sort()       # [1, 2, 3] (in place)
sorted_list = sorted(numbers)  # new list

sort modifies the list; sorted keeps the original. For reverse order use sort(reverse=True).

Reverse sorting

Use sort(reverse=True) for descending order:

numbers = [1, 3, 2]
numbers.sort(reverse=True)
print(numbers)  # [3, 2, 1]

Strings sort alphabetically by default: ["b", "a"].sort() → ["a", "b"]. reverse=True gives reverse alphabetical.

Reverse sorting is often used when a descending display is needed and it shortens the code.

Reverse sorting is often used when a descending display is needed and it shortens the code.

Reverse sorting is often used when a descending display is needed and it shortens the code.

Reverse sorting is often used when a descending display is needed and it shortens the code.

Practice Sort and print

Assign numbers = [3, 1, 2]. Call numbers.sort(). Print print(numbers).

Starter code

main.py
# Sort the list

Sample solution

main.py
numbers = [3, 1, 2]
numbers.sort()
print(numbers)

Expected output

[1, 2, 3]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between sort and sorted?

  • They are the same
  • sort is in place, sorted returns new Correct answer
  • sorted is in place, sort returns new
  • Both are in place

Explanation: sort modifies the list in place, sorted returns a new list.

2 Complete the sort call

Question
numbers = [3, 1, 2]
numbers.____()
Answer
numbers = [3, 1, 2]
numbers.sort()

Explanation: sort sorts the list in place.

3 Match the sorting concepts

Term Meaning
sort Sort in place
sorted New sorted list
reverse=True Descending
len Length

All lessons in Beginner