Sorting of Python Lists

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.

  1. Sort a list of integers in ascending order using the sort() method.
  2. Sort a list of strings in descending order using the sort() method.
  3. Sort a list of tuples by the second item in each tuple in ascending order using the sorted() function.
  4. Sort a list of dictionaries by the values of a specific key in descending order using the sorted() function.
  5. Sort a list of floating-point numbers in descending order using the sort() method.
  6. Sort a list of integers in descending order using the sorted() function.
  7. Sort a list of strings by the length of each string in ascending order using the sort() method.
  8. Sort a list of tuples by the sum of the items in each tuple in descending order using the sorted() function.
  9. Sort a list of dictionaries by the length of the values of a specific key in ascending order using the sorted() function.
  10. 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.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Β 194