Introduction
Sorting a Python List means arranging all the elements in a certain order. The order may be ascending or descending order. Python provides a variety of built-in functions and modules to sort data in lists, tuples, and other data structures.
In this article, we will explore some of the most common techniques for sorting lists in Python.
Sorting Lists using the sorted() function
The simplest way to sort a list in Python is to use the ‘sorted()‘ function. The ‘sorted()‘ function takes an iterable object as an argument, sorts it, and returns a new sorted list.
Here is an example of how to sort a list of integers using the ‘sorted()‘ function:
numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 5, 8]
The ‘sorted()‘ function can also be used to sort lists of strings and other data types. By default, the ‘sorted()‘ function sorts strings in alphabetical order.
fruits = ["banana", "apple", "orange", "kiwi"]
sorted_fruits = sorted(fruits)
print(sorted_fruits) # Output: ['apple', 'banana', 'kiwi', 'orange']
The ‘sorted()‘ function can also sort lists in reverse order by passing the ‘reverse=True‘ argument.
numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [8, 5, 3, 2, 1]
Sorting Lists using the sort() method
Python lists also provide a ‘sort()‘ method that can be used to sort lists in place. The ‘sort()‘ method modifies the original list instead of creating a new sorted list.
Here is an example of how to use the ‘sort()‘ method to sort a list of integers:
numbers = [5, 2, 8, 1, 3]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 5, 8]
Like the ‘sorted()‘ function, the ‘sort()‘ method can also be used to sort lists of strings and other data types.
fruits = ["banana", "apple", "orange", "kiwi"]
fruits.sort()
print(fruits) # Output: ['apple', 'banana', 'kiwi', 'orange']
The ‘sort()‘ method can also sort lists in reverse order by passing the ‘reverse=True‘ argument.
numbers = [5, 2, 8, 1, 3]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 3, 2, 1]
Sorting Lists using the key argument
Both the ‘sorted()‘ function and the ‘sort()‘ method allow the use of a ‘key‘ argument to customize the sorting order.
The ‘key‘ argument is used to specify a function that takes an item in the list as an argument and returns a value to be used for sorting. Here is an example of how to sort a list of strings based on the length of each string:
fruits = ["banana", "apple", "orange", "kiwi"]
sorted_fruits = sorted(fruits, key=len)
print(sorted_fruits) # Output: ['kiwi', 'apple', 'banana', 'orange']
In the above example, the list is sorted based on the length of the items present in the list. Here is another example of sorting a list of custom objects:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"{self.name} ({self.age})"
people = [
Person("Alice", 25),
Person("Bob", 20),
Person("Charlie", 30),
]
sorted_people = sorted(people, key=lambda p: p.age)
print(sorted_people) #Output: [Bob (20), Alice (25), Charlie (30)]
In this example, we defined a custom class called ‘Person‘ with two attributes, ‘name‘ and ‘age‘. We created a list of ‘Person‘ objects and sorted them based on the ‘age‘ attribute using the ‘key‘ parameter of the ‘sorted()‘ function.
sort vs sorted function
One of the significant differences between the two is that the ‘sort()‘ method modifies the original list while the ‘sorted()‘ function returns a new sorted list. In general, if we don’t want to modify the original list and want a new sorted list, we should use the ‘sorted()‘ function. If we want to sort the original list, we should use the ‘sort()‘ method.
Another difference is that the ‘sorted()‘ function can sort any iterable object in Python, including lists, tuples, and dictionaries, whereas the ‘sort()‘ method can only be used with lists.
Exercises
Try some exercises for practicing sorting Python lists.
- Sort a list of integers in ascending order using the sort() method.
- Sort a list of strings in descending order using the sort() method.
- Sort a list of tuples by the second item in each tuple in ascending order using the sorted() function.
- Sort a list of dictionaries by the values of a specific key in descending order using the sorted() function.
- Sort a list of floating-point numbers in descending order using the sort() method.
- Sort a list of integers in descending order using the sorted() function.
- Sort a list of strings by the length of each string in ascending order using the sort() method.
- Sort a list of tuples by the sum of the items in each tuple in descending order using the sorted() function.
- Sort a list of dictionaries by the length of the values of a specific key in ascending order using the sorted() function.
- Sort a list of integers in ascending order using the sorted() function, without modifying the original list.
These exercises should help you practice sorting Python lists using different methods and techniques. You can try implementing these exercises and experimenting with different approaches to get a better understanding of sorting in Python.