Python List sort()

The list's sort() method sorts the elements of a list.

Example

prime_numbers = [11, 3, 7, 5, 2]

# sort the list in ascending order prime_numbers.sort()
print(prime_numbers) # Output: [2, 3, 5, 7, 11]

sort() Syntax

numbers.sort(reverse, key)

The sort() method can take two optional keyword arguments:

  • reverse - By default False. If True is passed, the list is sorted in descending order.
  • key - Comparion is based on this function.

Sort in Descending order

We can sort a list in descending order by setting reverse to True.

numbers = [7, 3, 11, 2, 5]

# reverse is set to True numbers.sort(reverse = True)
print(numbers)

Output

[11, 7, 5, 3, 2]

Sort a List of Strings

The sort() method sorts a list of strings in dictionary order.

cities = ["Tokyo", "London", "Washington D.C"]

# sort in dictionary order
cities.sort()
print(f"Dictionary order: {cities}")

# sort in reverse dictionary order
cities.sort(reverse = True)
print(f"Reverse dictionary order: {cities}")

Output

Dictionary order: ['London', 'Tokyo', 'Washington D.C']
Reverse dictionary order: ['Washington D.C', 'Tokyo', 'London']

Reverse Strings Based on Length

The sort() method can sort items based on a function. For example,

text = ["abc", "wxyz", "gh", "a"]

# stort strings based on their length
text.sort(key = len)
print(text)

Output

['a', 'gh', 'abc', 'wxyz']

len is a built-in function that returns the length of a string.

Since we passed the len function as key, the strings are sorted based on their length.

Before we wrap up, let’s put your knowledge of Python list sort() to the test! Can you solve the following challenge?

Challenge:

Write a function to sort a list of strings by their length.

  • For Example, for input['apple', 'cherry', 'date'], the output should be ['date', 'apple', 'cherry']
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges