Back to Homepage
Tuesday 13 August 2024
8

How to sort in Python

Sorting is a common task in programming, allowing you to organize data in a particular order, whether ascending or descending. Python provides several built-in methods to sort lists, tuples, and other iterable collections, making it easy to manage and process data efficiently.

Sorting Lists with sort()

The sort() method is used to sort lists in place, meaning the original list is modified and sorted.

1. Basic Usage of sort():

my_list = [3, 1, 4, 1, 5, 9]
   my_list.sort()
   print(my_list)

Output:

[1, 1, 3, 4, 5, 9]
  • This code sorts my_list in ascending order.

2. Sorting in Descending Order:

Use the reverse=True argument to sort the list in descending order.

my_list = [3, 1, 4, 1, 5, 9]
   my_list.sort(reverse=True)
   print(my_list)

Output:

[9, 5, 4, 3, 1, 1]

3. Sorting with a Custom Key:

The key parameter allows you to specify a function to customize the sorting order. For example, sorting a list of strings by their length:

words = ["apple", "banana", "cherry", "date"]
   words.sort(key=len)
   print(words)

Output:

['date', 'apple', 'banana', 'cherry']
  • This code sorts the list of words based on their length.

Using the sorted() Function

The sorted() function returns a new sorted list from the elements of any iterable, leaving the original iterable unchanged.

4. Basic Usage of sorted():

my_list = [3, 1, 4, 1, 5, 9]
   sorted_list = sorted(my_list)
   print(sorted_list)
   print(my_list)  # Original list remains unchanged

Output:

[1, 1, 3, 4, 5, 9]
   [3, 1, 4, 1, 5, 9]

5. Sorting Tuples and Other Iterables:

sorted() works with any iterable, such as tuples, sets, or dictionaries.

my_tuple = (3, 1, 4, 1, 5, 9)
   sorted_tuple = sorted(my_tuple)
   print(sorted_tuple)

Output:

[1, 1, 3, 4, 5, 9]

6. Sorting in Descending Order:

Like sort(), sorted() also accepts the reverse=True argument.

my_list = [3, 1, 4, 1, 5, 9]
   sorted_list = sorted(my_list, reverse=True)
   print(sorted_list)

Output:

[9, 5, 4, 3, 1, 1]

7. Sorting with a Custom Key:

You can pass a function to the key parameter to define custom sorting criteria.

words = ["apple", "banana", "cherry", "date"]
   sorted_words = sorted(words, key=len)
   print(sorted_words)

Output:

['date', 'apple', 'banana', 'cherry']

Sorting Dictionaries by Keys or Values

To sort dictionaries, you can use sorted() with dictionary methods like .items() for key-value pairs.

8. Sorting by Keys:

my_dict = {'b': 3, 'a': 1, 'c': 2}
   sorted_by_keys = dict(sorted(my_dict.items()))
   print(sorted_by_keys)

Output:

{'a': 1, 'b': 3, 'c': 2}

9. Sorting by Values:

my_dict = {'b': 3, 'a': 1, 'c': 2}
   sorted_by_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))
   print(sorted_by_values)

Output:

{'a': 1, 'c': 2, 'b': 3}

Example: Sorting a List of Dictionaries

When working with a list of dictionaries, you can sort them based on a specific key within each dictionary.

10. Sorting a List of Dictionaries:

people = [
        {'name': 'Alice', 'age': 25},
        {'name': 'Bob', 'age': 30},
        {'name': 'Charlie', 'age': 20}
    ]
    sorted_people = sorted(people, key=lambda person: person['age'])
    print(sorted_people)

Output:

[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

Best Practices for Sorting in Python

  • Use sort() when you need to sort a list in place.
  • Use sorted() when you need to sort any iterable and keep the original unchanged.
  • Leverage the key parameter for custom sorting logic, such as sorting by length or specific attributes in complex data structures.
  • Combine reverse=True with key for descending custom sorts.

Official References

Sorting in Python is a powerful tool for organizing data, whether you're working with simple lists or complex data structures. By mastering the sort() method and the sorted() function, you can efficiently manage and process your data in a wide range of applications.

Hashtags:
python
Share:
Created by:
Author photo

Jorge García

Fullstack developer