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.