Python is a versatile programming language that offers a range of useful features, including the ability to sort lists. Sorting a list is a common task in programming, and Python provides several methods for achieving this. In this article, we’ll explore how to sort a list in Python and the different methods available to you.
Sorting a list in Python involves arranging the elements in a particular order. The order can be ascending or descending, depending on the requirements of your program. Python provides several built-in functions and methods for sorting lists. These methods work differently based on the data types of the list elements.
The sorted()
function is a built-in function in Python that returns a sorted list. The sorted()
function can be used to sort lists of any data type. Here’s an example:
numbers = [5, 2, 8, 1, 9]sorted_numbers = sorted(numbers)print(sorted_numbers)
Output:
[1, 2, 5, 8, 9]
The sort()
method is a built-in method in Python that sorts a list in place. The sort()
method can only be used to sort lists of homogeneous data types, such as integers, floats, or strings. Here’s an example:
numbers = [5, 2, 8, 1, 9]numbers.sort()print(numbers)
Output:
[1, 2, 5, 8, 9]
You can sort a list in reverse order by passing the reverse parameter to the sorted()
function or the sort()
method. Here’s an example:
numbers = [5, 2, 8, 1, 9]sorted_numbers = sorted(numbers, reverse=True)print(sorted_numbers)
Output:
[9, 8, 5, 2, 1]
numbers = [5, 2, 8, 1, 9]numbers.sort(reverse=True)print(numbers)
Output:
[9, 8, 5, 2, 1]
You can sort a list of dictionaries based on a specific key by passing a key function to the sorted()
function or the sort()
method. Here’s an example:
students = [{"name": "John", "age": 20},{"name": "Mary", "age": 18},{"name": "Tom", "age": 22}]sorted_students = sorted(students, key=lambda x: x["age"])print(sorted_students)
Output:
[{'name': 'Mary', 'age': 18}, {'name': 'John', 'age': 20}, {'name': 'Tom', 'age': 22}]
You can sort a list of tuples based on a specific index by passing a key function to the sorted()
function or the sort()
method. Here’s an example:
students = [("John", 20), ("Mary", 18), ("Tom", 22)]sorted_students = sorted(students, key=lambda x: x[1])print(sorted_students)
Output:
[('Mary', 18), ('John', 20), ('Tom', 22)]
students = [("John", 20), ("Mary", 18), ("Tom", 22)]students.sort(key=lambda x: x[1])print(students)
Output:
[('Mary', 18), ('John', 20), ('Tom', 22)]
You can sort a list of complex objects based on multiple attributes by passing a key function to the sorted()
function or the sort()
method. Here’s an example:
class Student:def __init__(self, name, age, gpa):self.name = nameself.age = ageself.gpa = gpadef __repr__(self):return f"{self.name} ({self.age}), GPA: {self.gpa}"students = [Student("John", 20, 3.5),Student("Mary", 18, 4.0),Student("Tom", 22, 3.0)]sorted_students = sorted(students, key=lambda x: (x.gpa, x.age), reverse=True)print(sorted_students)
Output:
[Mary (18), GPA: 4.0, John (20), GPA: 3.5, Tom (22), GPA: 3.0]
A key function is a function that takes an element from the list and returns a value that will be used as the sort key. You can pass a key function to the sorted()
function or the sort()
method to sort a list based on a specific attribute. Here’s an example:
names = ["John", "Mary", "Tom", "Jerry"]sorted_names = sorted(names, key=len)print(sorted_names)
Output:
['Tom', 'John', 'Mary', 'Jerry']
names = ["John", "Mary", "Tom", "Jerry"]names.sort(key=len)print(names)
Output:
['Tom', 'John', 'Mary', 'Jerry']
The sorted()
function returns a new sorted list, while the sort()
method sorts the list in place. If you don’t want to modify the original list, use the sorted()
function. If you don’t need the original list, use the sort()
method to save memory. Here’s an example:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]sorted_numbers = sorted(numbers)print(sorted_numbers)print(numbers)
Output:
[1, 1, 2, 3, 4, 5, 5, 6, 9][3, 1, 4, 1, 5, 9, 2, 6, 5]
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]numbers.sort()print(numbers)
Output:
[1, 1, 2, 3, 4, 5, 5, 6, 9]
In this article, we’ve covered various ways to sort a list in Python. Whether you’re dealing with a list of integers, strings, dictionaries, tuples, or complex objects, Python provides built-in functions and methods to help you sort your data efficiently. Remember to choose the right sorting algorithm based on the size and complexity of your data, and consider the performance trade-offs between sorting in place and creating a new sorted list.
sorted()
function or the sort()
method.sorted()
function or the sort()
method.sort()
method in Python?
The time complexity of the built-in sort()
method in Python is O(n log n).sorted()
function or the sort()
method.Quick Links
Legal Stuff
Social Media