Python Tutorial: List Sorting 🎯

beginner
21 min

Python Tutorial: List Sorting 🎯

Welcome to the List Sorting lesson! In this tutorial, we'll explore how to sort lists in Python. This skill is essential for many real-world programming tasks and projects. Let's dive in! 🏊‍♂️

What is List Sorting? 📝

List sorting is the process of arranging the elements of a list in a specific order, usually either ascending or descending. Python provides built-in functions to sort lists easily.

Why Sort Lists? 💡

Sorting lists can help us manage, analyze, and work with data more effectively. For example, sorting data in ascending order makes it easier to find the smallest or largest item.

How to Sort Lists in Python? 📝

Python provides two main functions for sorting lists: sort() and sorted(). The difference between these two functions lies in their scope: sort() modifies the list it's called on, while sorted() returns a new sorted list and leaves the original unchanged.

Example using sort() 📝

python
numbers = [5, 1, 9, 3, 7] numbers.sort() # The original list is sorted in-place print(numbers) # Output: [1, 3, 5, 7, 9]

Example using sorted() 📝

python
numbers = [5, 1, 9, 3, 7] sorted_numbers = sorted(numbers) # A new sorted list is created print(sorted_numbers) # Output: [1, 3, 5, 7, 9] print(numbers) # Output: [5, 1, 9, 3, 7] (The original list remains unchanged)

Sorting Lists with Custom Comparison 💡

You can sort lists using a custom comparison function. This can be useful when sorting objects with complex structures or when you need to sort by multiple criteria.

python
class Person: def __init__(self, name, age): self.name = name self.age = age people = [ Person('Alice', 25), Person('Bob', 19), Person('Charlie', 22), Person('David', 24) ] people.sort(key=lambda x: x.age) # Sort people by age people.sort(key=lambda x: x.name, reverse=True) # Sort people by name in descending order

Sorting Lists by Multiple Criteria 💡

To sort by multiple criteria, you can use a tuple of functions as the key argument to the sort() function. The first function is applied first, and the resulting list is then sorted by the second function.

python
people = [ ('Alice', 25, 1.75), ('Bob', 19, 1.82), ('Charlie', 22, 1.85), ('David', 24, 1.80) ] people.sort(key=lambda x: (x[1], x[2])) # First sort by age, then by height

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What function sorts a list in ascending order and modifies the list in-place?


By now, you should have a good understanding of sorting lists in Python. Sorting lists is a fundamental skill that will help you manage and analyze data effectively.

Up next, we'll explore how to use loops and conditional statements in Python. Stay tuned! 🚀