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! 🏊♂️
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.
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.
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.
sort() 📝numbers = [5, 1, 9, 3, 7]
numbers.sort() # The original list is sorted in-place
print(numbers) # Output: [1, 3, 5, 7, 9]sorted() 📝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)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.
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 orderTo 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.
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 heightWhat 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! 🚀