Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

How to Sort a Python List

  • Pankaj KumarPankaj Kumar
  • October 15, 2026
  • Python List
How to Sort a Python List

When a list’s values are out of order, sorting puts them in the order Python compares them. Python’s list.sort() changes the list itself, while sorted() returns a new sorted list and leaves the source unchanged.

I’ll show how to sort values in either direction and when to use sorted() to preserve the source list.

TL;DR

Use list.sort() to change a list in place, or sorted() to make a new sorted list while preserving the original.

  • Both sort ascending by default.
  • Pass reverse=True for descending order.
  • Pass key=callable to sort by a derived value.

What Does Sorting a Python List Do?

Sorting arranges list values according to their natural comparison order or a key you choose. Python offers list.sort(), which changes a list, and sorted(), which builds a new list from any iterable.

I ran sorted() on [5, 2, 4] and got [2, 4, 5]. The source stayed [5, 2, 4], so use sorted() when later code needs its original order.

Terminal output showing Python list sorting examples
Sort order, a custom key, and an unchanged original list

How to Sort a Python List Step by Step

Start with the list you want to order, then choose an in-place sort or a sorted copy based on whether the original order must remain available.

Step 1: Sort values in ascending or descending order

Call sort() with no arguments for ascending order. Set reverse=True for descending order. The sort uses that direction while comparing values, rather than reversing an already sorted list.

numbers = [8, 3, 1, 6, 2]
numbers.sort()
print("Ascending:", numbers)
numbers.sort(reverse=True)
print("Descending:", numbers)

Captured output from the named demo:

Ascending: [1, 2, 3, 6, 8]
Descending: [8, 6, 3, 2, 1]

Each call changes numbers. Use sorted(numbers, reverse=True) for a separate descending result.

Step 2: Sort strings without considering case

Pass str.casefold as key to compare text without case distinctions while retaining spelling.

words = ["pear", "Apple", "banana", "apricot"]
words.sort(key=str.casefold)
print("Case-insensitive:", words)

Output: Case-insensitive: [‘Apple’, ‘apricot’, ‘banana’, ‘pear’]. For locale-specific ordering, use locale.strxfrm instead.

Step 3: Sort records by one or more fields

The key callable receives one item and returns the value used for comparisons. A tuple key compares fields from left to right, so age sorts first and name breaks equal-age ties.

students = [("Mira", 24), ("Asha", 21), ("Dev", 21)]
students.sort(key=lambda student: (student[1], student[0]))
print("By age, then name:", students)

The captured result is [(‘Asha’, 21), (‘Dev’, 21), (‘Mira’, 24)]. For tuples, dictionaries or objects with named attributes, use operator.itemgetter or operator.attrgetter when that makes the selected field clearer. The Python list of tuples guide covers tuple data in more detail.

Edge Cases When Sorting Python Lists

Use the table to match each input or return-value issue with a concrete fix.

CaseSymptomFix
Assigning list.sort()The variable becomes None because sort() mutates the list.Call values.sort() on its own, or assign sorted(values).
Equal key valuesTied records need a secondary order.Sorting is stable. Add a tuple key when a specific tie-breaker is needed.
Integers mixed with stringsDirect comparison raises TypeError.Convert values to a shared comparable type with a key.
Digit strings like “2” and “10”Text order places “10” before “2”.Use key=int when every value is a digit string.

The signatures are list.sort(*, key=None, reverse=False) and sorted(iterable, /, *, key=None, reverse=False). Both key and reverse are keyword-only arguments.

For example, values.sort(key=len, reverse=True) orders strings by length. Every key result must be comparable with the others.

  • Choose heapq.nsmallest() or heapq.nlargest() when only a few extremes from a large iterable are needed.
  • Use the official Python Sorting HOWTO for stable sorting and key functions.

Conclusion

Choose the method that fits whether the source list can change. Add reverse or key only when the required order calls for them. See the official Python Sorting HOWTO and the Python list guide.

FAQ

These answers cover common variations on sorting Python lists.

How do I sort a Python list in descending order?

Call list.sort(reverse=True) to sort the list in place, or sorted(values, reverse=True) to return a new list.

How can I sort a list alphabetically without case differences?

Pass key=str.casefold, such as words.sort(key=str.casefold), to compare strings without case distinctions.

Does list.sort() return the sorted list?

No. list.sort() changes the existing list and returns None. Use sorted(values) to create and receive a new sorted list.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 264
Python String Functions: Methods by Task
Previous Post Python String Functions: Methods by Task
Next Post HashSet Hashtable Python: Choose the Right Types
HashSet Hashtable Python: Choose the Right Types

Related Posts

Python Reverse List: Methods and Examples

Python Reverse List: Methods and Examples

  • November 28, 2026
Python Empty List: How to Check It

Python Empty List: How to Check It

  • November 24, 2026
How to Square in Python: List Values

How to Square in Python: List Values

  • November 24, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.