Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use sorted(items) when you need a new sorted list, or items.sort() when you want to reorder a list in place. Add key= to sort by a derived value or object attribute, and reverse=True for descending order. Both methods are stable, so items with equal sort keys keep their original relative order.

Choose between sorted() and list.sort()

Both approaches sort values in ascending order by default, but they differ in what they accept and whether they keep the original collection intact.

Approach Input Effect Return value
sorted(iterable, key=None, reverse=False) Any iterable Creates a new sorted list; leaves the input unchanged The new list
list.sort(key=None, reverse=False) A list Reorders that list in place None

The Python Sorting HOW TO describes list.sort() as modifying a list in place and sorted() as building a new sorted list from an iterable: Python Sorting HOW TO.

Use sorted() to keep the original list

numbers = [5, 2, 3, 1, 4]
new_numbers = sorted(numbers)

print(new_numbers)  # [1, 2, 3, 4, 5]
print(numbers)      # [5, 2, 3, 1, 4]

Because sorted() accepts any iterable, it is also the appropriate choice when the input is not specifically a list but you still want a list containing the ordered values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use list.sort() to change the list

numbers = [5, 2, 3, 1, 4]
result = numbers.sort()

print(numbers)  # [1, 2, 3, 4, 5]
print(result)   # None

Do not assign the result of numbers.sort() when you need the sorted list: the method changes numbers and returns None.

Sort by a key, field, or object attribute

Pass a callable to key=. Python calls it once for each element and uses the resulting values to determine order. This is useful when the values you want to compare are derived from the elements rather than the elements themselves.

Sort strings without regard to case

words = ["pear", "Apple", "banana"]
case_insensitive = sorted(words, key=str.casefold)

print(case_insensitive)  # ['Apple', 'banana', 'pear']

str.casefold supplies a normalized comparison value; the original strings remain the returned elements.

Sort objects by an attribute

For objects with an age attribute, use that attribute as the key:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def by_age(student):
    return student.age

students_by_age = sorted(students, key=by_age)

The key function receives each student and returns the value used for ordering. You can use the same key= argument with students.sort() if the existing list should be reordered instead.

Sort in descending order

Set reverse=True to request descending order. It works with either API:

highest_first = sorted(numbers, reverse=True)
numbers.sort(reverse=True)

Descending order does not remove stability: items whose keys are equal still retain their relative order from the input.

Use stability to sort on multiple keys

A stable sort preserves the relative order of elements with equal keys. That lets you sort by a secondary field first, then by a primary field; the second pass orders the primary field while preserving the secondary ordering within each group of equal primary values. Python documents this technique in its Sorting HOW TO.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
students.sort(key=lambda student: student.age)       # secondary key
students.sort(key=lambda student: student.grade)     # primary key

After these passes, students are ordered by grade and, among students with the same grade, by age. When doing multiple passes, apply the least important key first and the most important key last.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Understand comparisons and special cases

Python sorting relies on the less-than operator (<) to compare values. If the values cannot be compared with one another, sorting can raise an exception rather than produce a meaningful order. Ensure that the elements or their key values are mutually comparable.

In CPython, mutating a list while its in-place sort is running has undefined behavior. Avoid changing the list from code that runs during that sort.

Locale-sensitive text

Default string ordering is not necessarily the ordering people expect for a particular language or locale. For locale-aware ordering, Python provides locale.strxfrm() as a key function; alternatively, use locale.strcoll() wrapped with functools.cmp_to_key(). See the Python Sorting HOW TO for the documented options.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.