Python List Sorting Methods: The Complete Guide
Sorting data is a fundamental task in almost any application—from processing user input to running complex data analysis algorithms. In Python, working with lists is intuitive, and the sorting tools offer both flexibility and powerful capabilities.
Python List Basics
Lists in Python are ordered, mutable collections of objects. They can store elements of different data types and provide convenient index-based access.
numbers = [5, 2, 9, 1, 5, 6]
words = ["banana", "apple", "cherry"]
mixed_list = [1, "hello", 3.14, True]
Core List Sorting Methods
Python offers two primary ways to sort lists: the sort() method and the sorted() function. Each has its own use cases and advantages.
sort() Method — In-Place Sorting
The sort() method modifies the original list and returns None. This approach is memory-efficient because it doesn't create a new list.
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # [1, 2, 5, 9]
sort() Parameters
The sort() method accepts the following parameters:
reverse: Controls the sort direction (True for descending, False for ascending)key: A function that defines the sorting criterion
numbers = [5, 2, 9, 1]
numbers.sort(reverse=True)
print(numbers) # [9, 5, 2, 1]
sorted() Function — Creating a New List
The sorted() function returns a new sorted list without modifying the original. This is useful when you need to preserve the original element order.
numbers = [5, 2, 9, 1]
new_numbers = sorted(numbers)
print(new_numbers) # [1, 2, 5, 9]
print(numbers) # [5, 2, 9, 1] — original list unchanged
Descending Sort with sorted()
numbers = [5, 2, 9, 1]
sorted_desc = sorted(numbers, reverse=True)
print(sorted_desc) # [9, 5, 2, 1]
Sorting Methods Comparison
| Method | Modifies List | Returns Value | Best Use Case |
|---|---|---|---|
| sort() | Yes | No (None) | When original order is not needed |
| sorted() | No | New list | When you need to keep original data |
Sorting Strings in Lists
Alphabetical Sorting
When sorting strings, Python uses lexicographic order by default:
words = ["banana", "apple", "cherry"]
words.sort()
print(words) # ['apple', 'banana', 'cherry']
Descending String Sort
words = ["banana", "apple", "cherry"]
words.sort(reverse=True)
print(words) # ['cherry', 'banana', 'apple']
Case Sensitivity in String Sorting
Case-Sensitive Sorting
By default, sorting is case-sensitive. Uppercase letters come before lowercase letters in the ASCII table:
words = ["Banana", "apple", "Cherry"]
print(sorted(words)) # ['Banana', 'Cherry', 'apple']
Case-Insensitive Sorting
To sort without considering case, use the key=str.lower parameter:
words = ["Banana", "apple", "Cherry"]
print(sorted(words, key=str.lower)) # ['apple', 'Banana', 'Cherry']