How to use the built-in sorted() function in Python programming?

PythonPythonBeginner
Practice Now

Introduction

Python's built-in sorted() function is a powerful tool for sorting data in your programs. In this tutorial, we'll explore the basics of using the sorted() function, as well as advanced sorting techniques to help you master this essential Python skill.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/lists -.-> lab-417843{{"`How to use the built-in sorted() function in Python programming?`"}} python/tuples -.-> lab-417843{{"`How to use the built-in sorted() function in Python programming?`"}} python/dictionaries -.-> lab-417843{{"`How to use the built-in sorted() function in Python programming?`"}} python/sets -.-> lab-417843{{"`How to use the built-in sorted() function in Python programming?`"}} python/build_in_functions -.-> lab-417843{{"`How to use the built-in sorted() function in Python programming?`"}} end

Introduction to the sorted() Function

The sorted() function is a built-in function in Python that allows you to sort elements in a sequence, such as a list, tuple, or string. It is a versatile function that can be used to sort data in various ways, making it a valuable tool in many programming tasks.

What is the sorted() Function?

The sorted() function takes an iterable (such as a list, tuple, or string) as input and returns a new sorted list. The original iterable remains unchanged. The function can sort elements in ascending or descending order, and can also sort based on a custom key function.

Syntax of the sorted() Function

The basic syntax of the sorted() function is:

sorted(iterable, key=None, reverse=False)
  • iterable: The sequence of elements to be sorted.
  • key: An optional function that takes one element from the iterable and returns a value to be used for sorting.
  • reverse: A boolean value that determines the sort order. If True, the elements will be sorted in descending order.

Advantages of the sorted() Function

The sorted() function offers several advantages:

  1. Flexibility: It can sort various data types, including numbers, strings, and custom objects.
  2. Efficiency: The sorted() function uses an efficient sorting algorithm, making it suitable for sorting large datasets.
  3. Immutability: The original iterable remains unchanged, as sorted() returns a new sorted list.
  4. Customization: The key and reverse parameters allow you to customize the sorting behavior.

Use Cases for the sorted() Function

The sorted() function can be used in a wide range of scenarios, such as:

  • Sorting a list of numbers or strings in ascending or descending order.
  • Sorting a list of custom objects based on a specific attribute.
  • Sorting a list of tuples or dictionaries based on one or more keys.
  • Performing case-insensitive sorting of strings.
  • Sorting a list of files or directories based on their names or modification times.

In the following sections, we will explore the usage of the sorted() function in more detail, covering basic sorting and advanced sorting techniques.

Sorting Basic Data Types

In this section, we will explore how to use the sorted() function to sort basic data types, such as numbers and strings.

Sorting Numbers

Sorting numbers in Python is straightforward using the sorted() function. Here's an example:

numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  ## Output: [1, 2, 5, 8, 9]

By default, the sorted() function sorts the elements in ascending order. To sort in descending order, you can use the reverse=True parameter:

numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)  ## Output: [9, 8, 5, 2, 1]

Sorting Strings

Sorting strings is also a common use case for the sorted() function. Here's an example:

names = ["John", "Alice", "Bob", "Charlie"]
sorted_names = sorted(names)
print(sorted_names)  ## Output: ['Alice', 'Bob', 'Charlie', 'John']

The sorted() function sorts the strings in alphabetical order by default. You can also perform case-insensitive sorting by using the key parameter with the str.lower() function:

names = ["John", "alice", "Bob", "charlie"]
sorted_names = sorted(names, key=str.lower)
print(sorted_names)  ## Output: ['alice', 'Bob', 'charlie', 'John']

Sorting Mixed Data Types

The sorted() function can also handle mixed data types, such as a list containing both numbers and strings. In this case, the elements are sorted based on their natural order (numbers first, then strings):

mixed_data = [5, "apple", 2, "banana", 8, "cherry"]
sorted_data = sorted(mixed_data)
print(sorted_data)  ## Output: [2, 5, 8, 'apple', 'banana', 'cherry']

By using the key parameter, you can customize the sorting behavior for mixed data types. For example, to sort the strings in reverse alphabetical order:

mixed_data = [5, "apple", 2, "banana", 8, "cherry"]
sorted_data = sorted(mixed_data, key=lambda x: isinstance(x, str) and x.lower() or x)
print(sorted_data)  ## Output: [8, 5, 2, 'cherry', 'banana', 'apple']

In the next section, we will explore more advanced sorting techniques using the sorted() function.

Advanced Sorting Techniques

In this section, we will explore more advanced sorting techniques using the sorted() function, including sorting custom objects, sorting dictionaries, and using a custom key function.

Sorting Custom Objects

Suppose you have a list of custom objects, and you want to sort them based on a specific attribute. You can use the key parameter of the sorted() function to achieve this. Here's an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

people = [
    Person("John", 35),
    Person("Alice", 28),
    Person("Bob", 42)
]

## Sort by age
sorted_people = sorted(people, key=lambda x: x.age)
print(sorted_people)  ## Output: [Person('Alice', 28), Person('John', 35), Person('Bob', 42)]

## Sort by name
sorted_people = sorted(people, key=lambda x: x.name)
print(sorted_people)  ## Output: [Person('Alice', 28), Person('Bob', 42), Person('John', 35)]

Sorting Dictionaries

Sorting dictionaries can be useful when you need to retrieve the keys or values in a specific order. Here's an example:

person = {
    "name": "John",
    "age": 35,
    "city": "New York"
}

## Sort by keys
sorted_person = sorted(person.items(), key=lambda x: x[0])
print(sorted_person)  ## Output: [('age', 35), ('city', 'New York'), ('name', 'John')]

## Sort by values
sorted_person = sorted(person.items(), key=lambda x: x[1])
print(sorted_person)  ## Output: [('name', 'John'), ('age', 35), ('city', 'New York')]

Using a Custom Key Function

The key parameter of the sorted() function allows you to define a custom function that determines the sorting order. This can be useful when you need to sort elements based on a complex logic or a combination of attributes.

For example, let's say you have a list of tuples representing student records, and you want to sort them first by grade (descending), then by name (ascending):

student_records = [
    ("John", 85),
    ("Alice", 92),
    ("Bob", 78),
    ("Charlie", 90)
]

sorted_records = sorted(student_records, key=lambda x: (-x[1], x[0]))
print(sorted_records)  ## Output: [('Alice', 92), ('Charlie', 90), ('John', 85), ('Bob', 78)]

In the custom key function, we use -x[1] to sort the grades in descending order, and x[0] to sort the names in ascending order.

By leveraging the flexibility of the sorted() function and custom key functions, you can sort data in a wide variety of ways to meet your specific requirements.

Summary

The sorted() function in Python is a versatile tool that allows you to sort a wide range of data types. By understanding the basics and exploring advanced sorting techniques, you can optimize your Python code and improve the efficiency of your data processing tasks. Whether you're a beginner or an experienced Python programmer, this tutorial will provide you with the knowledge and skills to effectively use the sorted() function in your Python projects.

Other Python Tutorials you may like