Python – Sort Lists
Python makes it easy to sort lists using built-in methods. Lists can be sorted in ascending or descending order, either in-place or by returning a new list.
You can sort numbers, strings, or even custom objects using sort()
or sorted()
.
List for Reference
numbers = [4, 2, 9, 1, 5]
fruits = ["banana", "apple", "cherry"]
1. sort()
– Sort the List In-Place
The list.sort()
method sorts the list permanently, modifying the original list.
Example 1: Sort Numbers (Ascending)
numbers = [4, 2, 9, 1, 5]
numbers.sort()
print(numbers)
Output:
[1, 2, 4, 5, 9]
Example 2: Sort Strings (Alphabetically)
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits)
Output:
['apple', 'banana', 'cherry']
2. sorted()
– Return a New Sorted List
The sorted()
function returns a new sorted list, leaving the original unchanged.
Example:
numbers = [4, 2, 9, 1, 5]
sorted_numbers = sorted(numbers)
print("Original:", numbers)
print("Sorted:", sorted_numbers)
Output:
Original: [4, 2, 9, 1, 5]
Sorted: [1, 2, 4, 5, 9]
Great when you need to keep the original list intact.
3. Sort in Descending Order
Use reverse=True
with either sort()
or sorted()
.
Example:
numbers = [4, 2, 9, 1, 5]
numbers.sort(reverse=True)
print(numbers)
Output:
[9, 5, 4, 2, 1]
4. Custom Sort with key=
You can customize sorting using the key
parameter, such as sorting by length, last character, etc.
Example: Sort Strings by Length
fruits = ["banana", "apple", "kiwi", "cherry"]
fruits.sort(key=len)
print(fruits)
Output
['kiwi', 'apple', 'banana', 'cherry']
5. Sort Case-Insensitive
By default, Python considers uppercase before lowercase in ASCII. Use str.lower
to sort case-insensitively.
Example:
names = ["Alice", "bob", "Charlie", "anna"]
names.sort(key=str.lower)
print(names)
Output:
['Alice', 'anna', 'bob', 'Charlie']
Summary of Sort Methods
Method | Description | In-Place | Returns New |
---|---|---|---|
list.sort() | Sorts list in-place | ✅ | ❌ |
sorted(list) | Returns a new sorted list | ❌ | ✅ |
reverse=True | Sorts in descending order | ✅ | ✅ (with sorted ) |
key=function | Custom sorting logic | ✅ | ✅ |
Things to Remember
sort()
works only on listssorted()
works on any iterable (lists, tuples, strings, etc.)- Don't use
sort()
on mixed-type lists (e.g., integers and strings)