Lesson Introduction

Sorting is a fundamental operation in data processing and algorithms. Whether you're organizing a list of names, arranging numerical data, or ordering objects by attributes, sorting helps you manage and analyze data efficiently. Today, we're exploring the sorted function in Python. By the end of this lesson, you will understand how to use the sorted function to sort data in various ways, leveraging its powerful and flexible features.

Basic Usage: Part 1

Let's start with the basics. The sorted function returns a new list containing all items from the original iterable in ascending order. It doesn't modify the original list but returns a sorted result.

Here's a simple example:

In this code, we define a numbers list and use the sorted function to sort it in ascending order.

Basic Usage: Part 2

To sort in descending order, set the reverse parameter to True in the sorted function:

Sorting a List of Objects Based on a Field (Part 1)

When dealing with a list of objects, you can sort the objects based on a specific attribute using the key parameter in sorted.

Here's how you can sort students by their ages:

In this example, the key parameter is set to a lambda function that extracts the age attribute from each Student object. The sorted function uses the values returned by this lambda function to sort the list of students.

Sorting a List of Objects Based on a Field (Part 2)

To handle ties when sorting by one attribute, return a tuple from the key function where the first element is the primary sort key and subsequent elements are tie-breakers. For example, sort students by age and name:

Lesson Summary

In this lesson, we've explored the versatile sorted function in Python. You now understand how to:

  • Sort lists in ascending and descending order.
  • Sort lists of objects based on attributes.
  • Handle ties with multiple sort keys.

The sorted function is powerful and flexible, making it essential in any Python programmer's toolkit. Next, you will get hands-on practice to solidify your understanding and improve your coding skills.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal