Python sorted() - Sort Iterable

Updated on November 22, 2024
sorted() header image

Introduction

The sorted() function in Python is a built-in utility that arranges elements from any iterable (like lists, tuples, and dictionaries) into a specific order (ascending or descending). This function is integral to data manipulation and preparation in Python, as sorting can often be a preliminary step in data analysis and visualization tasks.

In this article, you will learn how to use the sorted() function to sort various types of iterables. The discussion will cover basic sorting, customized sorting with key functions, and reverse sorting. Explore how this versatile function can be used to handle different data types and structures effectively.

Sorting Basics

Sort a List

  1. Create a list of integers.

  2. Use the sorted() function to sort the list.

    python
    numbers = [5, 1, 8, 3, 2]
    sorted_numbers = sorted(numbers)
    print(sorted_numbers)
    

    This code snippet sorts the list numbers. The sorted() function returns a new list sorted_numbers with elements in ascending order [1, 2, 3, 5, 8].

Sort a String (Alphabetical Order)

  1. Define a string.

  2. Apply sorted() to sort the characters of the string.

    python
    greeting = "hello"
    sorted_greeting = sorted(greeting)
    print(sorted_greeting)
    

    Here, sorted() converts the string into a list of characters and sorts them alphabetically, resulting in ['e', 'h', 'l', 'l', 'o'].

Customizing Sort with Key Functions

Sort by Length

  1. Create a list of strings.

  2. Sort the list by the length of its elements using sorted() with a key parameter.

    python
    words = ["python", "is", "a", "wonderful", "language"]
    sorted_words = sorted(words, key=len)
    print(sorted_words)
    

    The key=len tells sorted() to use the length of each element as the criterion for sorting. The output will be ['a', 'is', 'python', 'language', 'wonderful'], sorted based on the number of characters each string contains.

Sort by Custom Function

  1. Define a custom function that influences the sorting order.

  2. Use this function as the key in sorted().

    python
    def custom_sort(word):
        return word[-1]  # sorts by the last character of the string
    
    words = ["banana", "apple", "cherry"]
    sorted_by_last = sorted(words, key=custom_sort)
    print(sorted_by_last)
    

    This snippet sorts the words list based on the last letter of each word, resulting in ['banana', 'apple', 'cherry'] because 'a', 'e', and 'y' are the last letters, respectively.

Reverse Sorting

Sorting in Descending Order

  1. Take any iterable.

  2. Use the reverse parameter in the sorted() function to sort in descending order.

    python
    numbers = [5, 1, 8, 3, 2]
    descending_numbers = sorted(numbers, reverse=True)
    print(descending_numbers)
    

    Setting reverse=True sorts the list numbers in descending order, producing [8, 5, 3, 2, 1].

Conclusion

The sorted() function in Python provides a straightforward yet powerful way to order elements from any iterable. Utilizing this function with different types of data, custom key functions, and reverse ordering options allows for flexible data manipulation. By mastering the techniques discussed, enhance the organization and preparation of data in your Python projects, ensuring that you can handle sorting tasks with ease and efficiency.