Sorting Lists in Python: A Comprehensive Guide
Data sorting is a crucial element in almost any application, from processing user input to complex data analysis algorithms. In Python, working with lists is intuitively simple. Sorting tools provide flexibility and powerful capabilities.
Basics of Working with Lists in Python
Lists in Python are ordered, mutable collections of objects. They allow you to store elements of various data types and provide convenient access to them by index.
numbers = [5, 2, 9, 1, 5, 6]
words = ["banana", "apple", "cherry"]
mixed_list = [1, "hello", 3.14, True]
Main Methods for Sorting Lists
Python provides two main ways to sort lists: the sort() method and the sorted() function. Each has its own characteristics and applications.
The sort() Method — In-Place Sorting
The sort() method modifies the original list and returns None. This approach is memory-efficient because it does not create a new list.
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # [1, 2, 5, 9]
Parameters of the sort() Method
The sort() method accepts the following parameters:
reverse: Determines the sorting direction (Truefor descending,Falsefor ascending).key: A function that defines the sorting criterion.
numbers = [5, 2, 9, 1]
numbers.sort(reverse=True)
print(numbers) # [9, 5, 2, 1]
The 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 order of elements.
numbers = [5, 2, 9, 1]
new_numbers = sorted(numbers)
print(new_numbers) # [1, 2, 5, 9]
print(numbers) # [5, 2, 9, 1] — original list is not changed
Sorting in Descending Order with sorted()
numbers = [5, 2, 9, 1]
sorted_desc = sorted(numbers, reverse=True)
print(sorted_desc) # [9, 5, 2, 1]
Comparison of Sorting Methods
| Method | Modifies List | Returns Value | Use Case |
|---|---|---|---|
sort() |
Yes | No (None) |
When the original order is not needed |
sorted() |
No | New List | When you need to preserve the original data |
Sorting Strings in Lists
Alphabetic Sorting
When sorting strings, Python uses lexicographical order by default:
words = ["banana", "apple", "cherry"]
words.sort()
print(words) # ['apple', 'banana', 'cherry']
Sorting in Descending Order
words = ["banana", "apple", "cherry"]
words.sort(reverse=True)
print(words) # ['cherry', 'banana', 'apple']
Working with Case When Sorting Strings
Case Sensitivity
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']
Ignoring Case
To sort case-insensitively, use the key=str.lower parameter:
words = ["Banana", "apple", "Cherry"]
print(sorted(words, key=str.lower)) # ['apple', 'Banana', 'Cherry']
Sorting Complex Data Structures
Sorting a List of Dictionaries
When working with complex data structures, such as lists of dictionaries, use the key parameter with lambda functions:
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 90},
{"name": "Charlie", "grade": 80}
]
sorted_students = sorted(students, key=lambda x: x["grade"])
print(sorted_students)
Result:
[{'name': 'Charlie', 'grade': 80}, {'name': 'Alice', 'grade': 85}, {'name': 'Bob', 'grade': 90}]
Multi-Criteria Sorting
To sort by multiple criteria, use a tuple in the key parameter:
students = [
{"name": "Alice", "grade": 85, "age": 20},
{"name": "Bob", "grade": 85, "age": 19},
{"name": "Charlie", "grade": 90, "age": 21}
]
sorted_students = sorted(students, key=lambda x: (x["grade"], x["age"]))
Sorting Numbers with Mathematical Functions
Sorting by Absolute Value
Sometimes you need to sort not by direct value, but by a calculated criterion:
import math
numbers = [-5, 3, -2, 8, -1]
sorted_numbers = sorted(numbers, key=abs)
print(sorted_numbers) # [-1, -2, 3, -5, 8]
Sorting by Square of a Number
numbers = [-3, 1, -2, 4, -1]
sorted_by_square = sorted(numbers, key=lambda x: x**2)
print(sorted_by_square) # [-1, 1, -2, -3, 4]
Using Custom Functions for Sorting
Sorting by String Length
def by_length(word):
return len(word)
words = ["Python", "AI", "Machine Learning", "Data"]
sorted_words = sorted(words, key=by_length)
print(sorted_words) # ['AI', 'Data', 'Python', 'Machine Learning']
Sorting by Number of Vowels
def count_vowels(word):
vowels = "aeiouAEIOU"
return sum(1 for char in word if char in vowels)
words = ["hello", "world", "python", "programming"]
sorted_by_vowels = sorted(words, key=count_vowels)
print(sorted_by_vowels) # ['world', 'python', 'hello', 'programming']
Using Classes for Custom Sorting
Defining a Comparison Method in a Class
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __lt__(self, other):
return self.grade < other.grade
def __repr__(self):
return f"Student('{self.name}', {self.grade})"
students = [Student("Alice", 85), Student("Bob", 90), Student("Charlie", 80)]
students.sort()
for s in students:
print(f"{s.name}: {s.grade}")
Using the operator Module for Sorting
from operator import attrgetter
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person('{self.name}', {self.age})"
people = [Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20)]
sorted_people = sorted(people, key=attrgetter('age'))
print(sorted_people)
High-Performance Sorting with NumPy
For working with large numerical arrays, the NumPy library provides optimized sorting algorithms:
import numpy as np
arr = np.array([5, 2, 9, 1, 8, 3])
sorted_arr = np.sort(arr)
print(sorted_arr) # [1 2 3 5 8 9]
# Sorting in descending order
sorted_desc = np.sort(arr)[::-1]
print(sorted_desc) # [9 8 5 3 2 1]
Sorting Multidimensional Arrays
import numpy as np
arr_2d = np.array([[3, 1, 4], [2, 5, 1], [1, 3, 2]])
sorted_2d = np.sort(arr_2d, axis=1) # Sorting by rows
print(sorted_2d)
Advanced Sorting Techniques
Stable Sorting
Python uses a stable sorting algorithm (Timsort), which preserves the relative order of equal elements:
students = [
("Alice", 85),
("Bob", 90),
("Charlie", 85),
("David", 90)
]
# Sorting by grade will preserve the order of students with the same grades
sorted_students = sorted(students, key=lambda x: x[1])
Reverse Sorting Without the reverse Parameter
numbers = [5, 2, 9, 1]
sorted_reverse = sorted(numbers, key=lambda x: -x)
print(sorted_reverse) # [9, 5, 2, 1]
Frequently Asked Questions
How does the key parameter work in the sorted() function?
The key parameter takes a function that defines the sorting criterion. The function is applied to each element of the list, and the sorting happens based on the returned values.
What is the difference between sorted() and list.sort()?
The sorted() function creates a new list and does not modify the original. The sort() method modifies the existing list in place and returns None.
Can I sort lists by multiple criteria?
Yes, by using a tuple in the key parameter:
sorted(items, key=lambda x: (x["field1"], x["field2"]))
How to sort a list of numbers in descending order?
numbers.sort(reverse=True)
# or
sorted_numbers = sorted(numbers, reverse=True)
How to make sorting case-insensitive?
sorted(words, key=str.lower)
How to sort a list in reverse order?
numbers.reverse() # Simply reverses the order of elements
# or
sorted(numbers, reverse=True) # Sorts in descending order
Practical Recommendations
By mastering the sort() and sorted() methods, as well as working with the key and reverse parameters, you can effectively sort any data. From simple numbers to complex data structures.
Experiment with custom sorting functions and lambda expressions. This will unlock additional possibilities when working with data and help solve more complex information processing tasks.
The Future of AI in Mathematics and Everyday Life: How Intelligent Agents Are Already Changing the Game
Experts warned about the risks of fake charity with AI
In Russia, universal AI-agent for robots and industrial processes was developed