sort() – Sort List

Overview

The sort() method in Python is a built-in list method used to sort the elements of a list in a specific order, either ascending or descending. This method modifies the original list in place and offers several customization options through its parameters. The sort() method is particularly useful for arranging data in a desired sequence for better readability, analysis, or processing.

Syntax

The syntax for the sort() method is:

list.sort(key=None, reverse=False)
  • list: The name of the list you want to sort.
  • key (optional): A function that serves as a key for the sort comparison. Defaults to None.
  • reverse (optional): A boolean value. If True, the list elements are sorted in descending order. Defaults to False.

Basic Usage

Using the sort() method, you can sort a list in ascending order by default. Here is an example:

# Create a list with some elements
numbers = [5, 2, 9, 1, 5, 6]

# Sort the list in ascending order
numbers.sort()

# Print the sorted list
print(numbers)  # Output: [1, 2, 5, 5, 6, 9]

Sorting in Descending Order

To sort a list in descending order, you can use the reverse parameter:

# Create a list with some elements
numbers = [5, 2, 9, 1, 5, 6]

# Sort the list in descending order
numbers.sort(reverse=True)

# Print the sorted list
print(numbers)  # Output: [9, 6, 5, 5, 2, 1]

Using the key Parameter

The key parameter allows you to specify a function that determines the sort order. This is particularly useful for sorting complex objects or custom sorting criteria.

Sorting by Length of Strings

# Create a list of strings
words = ["banana", "apple", "cherry", "blueberry"]

# Sort the list by the length of the strings
words.sort(key=len)

# Print the sorted list
print(words)  # Output: ["apple", "banana", "cherry", "blueberry"]

Sorting by Custom Function

You can use any custom function with the key parameter to sort the list based on custom criteria.

# Create a list of tuples
students = [("John", 75), ("Jane", 85), ("Dave", 80)]

# Define a custom function to use as a key
def get_grade(student):
    return student[1]

# Sort the list by grades
students.sort(key=get_grade)

# Print the sorted list
print(students)  # Output: [("John", 75), ("Dave", 80), ("Jane", 85)]
# Create a list of tuples
students = [("John", 75), ("Jane", 85), ("Dave", 80)]

# Define a custom function to use as a key
def get_grade(student):
    return student[1]

# Sort the list by grades
students.sort(key=get_grade)

# Print the sorted list
print(students)  # Output: [("John", 75), ("Dave", 80), ("Jane", 85)]

Stability of sort()

Python’s sort() method is stable, meaning that when multiple records have the same key, their original order is preserved in the sorted list. This property can be useful for complex sorting scenarios.

Comparison with Other Sorting Methods

While the sort() method sorts a list in place, Python provides other ways to sort data:

Using sorted()

The sorted() function returns a new sorted list from the elements of any iterable, leaving the original iterable unchanged.

# Create a list with some elements
numbers = [5, 2, 9, 1, 5, 6]

# Create a sorted list without modifying the original
sorted_numbers = sorted(numbers)

# Print the sorted list and the original list
print(sorted_numbers)  # Output: [1, 2, 5, 5, 6, 9]
print(numbers)         # Output: [5, 2, 9, 1, 5, 6]

Performance Considerations

The sort() method has a time complexity of O(n log n) on average, where n is the number of elements in the list. Python’s built-in sorting algorithm is Timsort, which is a hybrid sorting algorithm derived from merge sort and insertion sort. It is highly efficient for real-world data and performs well on various types of datasets.

Examples

Sorting a List of Dictionaries

# Create a list of dictionaries
students = [
    {"name": "John", "grade": 75},
    {"name": "Jane", "grade": 85},
    {"name": "Dave", "grade": 80}
]

# Sort the list of dictionaries by grade
students.sort(key=lambda student: student["grade"])

# Print the sorted list
print(students)
# Output: [{'name': 'John', 'grade': 75}, {'name': 'Dave', 'grade': 80}, {'name': 'Jane', 'grade': 85}]

Sorting with Multiple Criteria

# Create a list of tuples
students = [("John", 75), ("Jane", 85), ("Dave", 80), ("Alice", 80)]

# Sort the list by grade, then by name
students.sort(key=lambda student: (student[1], student[0]))

# Print the sorted list
print(students)
# Output: [("John", 75), ("Alice", 80), ("Dave", 80), ("Jane", 85)]

Conclusion

The sort() method is a powerful and flexible tool for sorting lists in Python. Its ability to sort based on custom criteria and handle both ascending and descending order makes it suitable for a wide range of applications.