PythonPython ListsList sorting

How do you sort a list?

Question 85 of 88 · Updated

On this page

Use items.sort() to arrange a list in ascending order. Pass reverse=True for descending order or key to choose what determines the order. The method changes the original list and returns None.

Sort numbers#

Imagine arranging product prices from lowest to highest, then highest to lowest.

PYTHON
prices = [299, 99, 199] prices.sort() print(prices) # [99, 199, 299] prices.sort(reverse=True) print(prices) # [299, 199, 99]

Sort by a specific field#

For a student leaderboard, sort by marks rather than names.

PYTHON
students = [('Asha', 75), ('Ravi', 92), ('Neha', 75)] students.sort(key=lambda student: student[1], reverse=True) print(students) # [('Ravi', 92), ('Asha', 75), ('Neha', 75)]

The key function extracts the marks from each tuple. Python's sort is stable: Asha and Neha have equal marks, so their original relative order is preserved.

Useful sorting options#

ExpressionPurpose
items.sort()Ascending order
items.sort(reverse=True)Descending order
names.sort(key=str.lower)Case-insensitive ordering using lowercase keys
items.sort(key=len)Shortest to longest for strings or other sized elements

Common mistakes#

  • Do not write items = items.sort(): the return value is None.
  • Incompatible values, such as integers and strings in the same list, can raise TypeError. Use a suitable key or normalize the data first.
  • Sorting is different from reversing: sorting arranges by value or key; reversing only flips the existing order.

Takeaway: Use sort() when you want to reorder the existing list. If you need a separate sorted list, use sorted(); the next lesson compares both.

Official references#

References

  1. 1.
    Python Sorting HOW TOdocs.python.org
  2. 2.
    Python list methodsdocs.python.org

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design