Sort Lists
Sorting lists is a common task in Python when you need to organize data in a specific order.
Python provides powerful and flexible ways to sort lists in-place or by creating a new sorted list.
Sort a List Using sort()
The
sort() method sorts the list in ascending order by default and modifies the original list.python
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)
python
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits)
Sort in Descending Order
Use the
reverse=True argument.python
numbers = [3, 1, 4, 2]
numbers.sort(reverse=True)
print(numbers)
python
fruits = ["banana", "apple", "cherry"]
fruits.sort(reverse=True)
print(fruits)
Sort a List Using sorted()
The
sorted() function returns a new sorted list without changing the original.python
numbers = [5, 2, 9, 1]
new_list = sorted(numbers)
print(new_list)
print(numbers)
python
words = ["cat", "elephant", "dog"]
print(sorted(words))
Sort by Length Using key
The
key parameter allows custom sorting logic.python
words = ["apple", "banana", "kiwi"]
words.sort(key=len)
print(words)
python
numbers = ["10", "2", "30"]
numbers.sort(key=int)
print(numbers)
Sort List of Tuples
python
data = [(1, 3), (4, 1), (2, 2)]
data.sort()
print(data)
python
data.sort(key=lambda x: x[1])
print(data)
Sort with Case Sensitivity
By default, uppercase letters come first.
python
names = ["apple", "Banana", "cherry"]
names.sort()
print(names)
Case-Insensitive Sort
python
names.sort(key=str.lower)
print(names)
Reverse a List Without Sorting
python
numbers = [1, 2, 3]
numbers.reverse()
print(numbers)
Sort Numeric vs String Values
python
values = ["100", "20", "3"]
values.sort()
print(values)
python
values.sort(key=int)
print(values)
Sorting Nested Lists
python
matrix = [[3, 1], [1, 5], [2, 2]]
matrix.sort()
print(matrix)
python
matrix.sort(key=lambda x: x[1])
print(matrix)
Common Mistakes
Expecting sort() to Return a List
python
numbers = [3, 2, 1]
result = numbers.sort()
print(result)
sort() returns None.Mixing Incompatible Types
python
# numbers = [1, "2", 3]
# numbers.sort() # TypeError
Performance Note
sort()is faster for large listssorted()is useful when original order must be preserved- Python uses Timsort, which is efficient and stable
Summary
sort()modifies the original listsorted()returns a new listreverse=Truesorts descendingkeyallows custom sorting logic- Sorting is case-sensitive by default
- Avoid mixing incompatible types