w3resource

Python List: sort() Method

sort() Method

The sort() method is used to sort the items of a given list.

Visual Explanation:

Python List: sort() method

Syntax:

list.sort(*, key=None, reverse=False)

Parameter:

  • Key: Optional. A function that specifies the sorting criteria.
  • reverse - Default value of reverse is False. False sort the list in ascending order and True sort the list in descending order.

Return Value:

The sort() method doesn't return any value. Rather, it modifies the original list.

Example 1: Sort a list in ascending/descending order


colors = ['Red', 'Green', 'Orange', 'Pink']
print("Original List:")
print(colors)
colors.sort()
print('\nSort the said list in ascending order:')
print(colors)
print('\nSort the said list in descending order:')
colors.sort(reverse=True)
print(colors)

Output:

Original List:
['Red', 'Green', 'Orange', 'Pink']

Sort the said list in ascending order:
['Green', 'Orange', 'Pink', 'Red']

Sort the said list in descending order:
['Red', 'Pink', 'Orange', 'Green']

Example 3: Sort the list using key


def test(data):
  return data['Math']
students = [
  {'V': 'Jenny Vang', 'Math': 99},
  {'V': 'Allan Barker', 'Math': 100},
  {'V': 'Bradley Whitney', 'Math': 97},
  {'V': 'Ellie Ross', 'Math': 98},
  {'V': 'Antoine Booker', 'Math': 99}
]
print("Original students list:")
print(students)
students.sort(key=test)
print("\nStudents list after sorting on Math marks:")
print(students)

Output:

Original students list:
[{'V': 'Jenny Vang', 'Math': 99}, {'V': 'Allan Barker', 'Math': 100}, {'V': 'Bradley Whitney', 'Math': 97}, {'V': 'Ellie Ross', 'Math': 98}, {'V': 'Antoine Booker', 'Math': 99}]

Students list after sorting on Math marks:
[{'V': 'Bradley Whitney', 'Math': 97}, {'V': 'Ellie Ross', 'Math': 98}, {'V': 'Jenny Vang', 'Math': 99}, {'V': 'Antoine Booker', 'Math': 99}, {'V': 'Allan Barker', 'Math': 100}]

Python Code Editor:

Previous: Python List reverse() Method
Next: Python List

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.