8.1 List Sorting
Sorting a list in Python is an important operation and it allows you to organize data for easier analysis or presentation. Python offers several ways to sort lists, each of which can be useful depending on the task and desired results.
The sort()
Method
The sort()
method sorts a list in place, meaning it changes the original list. It's super efficient and allows you to customize the sorting with arguments.
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # Outputs [1, 2, 5, 9]
You can sort a list in reverse order by setting the reverse=True
parameter.
numbers = [5, 2, 9, 1]
numbers.sort(reverse=True)
print(numbers) # Outputs [9, 5, 2, 1]
The sorted()
Function
The sorted()
function creates a new list that is a sorted version of the original. The original list remains unchanged, which often makes sorted()
the preferred choice when you need to keep the original data intact.
numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Outputs [1, 2, 5, 9]
print(numbers) # Original list is unchanged [5, 2, 9, 1]
It's important to remember that sort()
modifies the original list, while sorted()
returns a new sorted list, leaving the original unchanged. Use sort()
if you need to modify the data in place, and sorted()
if you want to keep the original order.
8.2 Sorting by Key
Sometimes you need complex sorting scenarios or sorting while ignoring certain parameters. This is where "key sorting" comes to the rescue. To use it, you need to pass a special parameter — key
to the sort()
method or sorted()
function.
The value for the key
parameter should be a function that will be used for comparing elements.
Case Insensitive String Comparison
All strings are converted to lowercase before comparison
alist = ["banana", "Orange", "Kiwi", "cherry"]
alist.sort(key=str.lower)
print(alist) # Outputs ['banana', 'cherry', 'Kiwi', 'Orange']
Example of Sorting a List of Tuples
Suppose you have a list of students where each element is a tuple, containing the student's name and their grade. You want to sort the students by their grades:
students = [('Alice', 88), ('Bob', 75), ('Carol', 96)]
def get_grade(student):
return student[1]
students.sort(key=get_grade)
print(students) # Outputs [('Bob', 75), ('Alice', 88), ('Carol', 96)]
Example of Sorting a List of Dictionaries
Or you have a list of dictionaries where each dictionary contains information about students. To sort them by grades, you need to write code like this:
students = [
{'name': 'Alice', 'grade': 88},
{'name': 'Bob', 'grade': 75},
{'name': 'Carol', 'grade': 96}
]
def get_grade(student):
return student['grade']
sorted_students = sorted(students, key=get_grade)
print(sorted_students) # Outputs [{'name': 'Bob', 'grade': 75}, {'name': 'Alice', 'grade': 88}, {'name': 'Carol', 'grade': 96}]
GO TO FULL VERSION