Sorting Data
Sorting Data
Sometimes data is easier to use when it is in order.
For example:
- Lowest price to highest price
- A to Z names
- Highest score first
- Shortest word first
Python gives us easy ways to sort data.
What Does Sorting Mean?
Sorting means arranging data in order.
Common types:
- Ascending = small to large, A to Z
- Descending = large to small, Z to A
Sorting a List with sort()
Use sort() to sort the original list.
numbers = [3, 1, 2]
numbers.sort()
print(numbers)
Output
[1, 2, 3]
Descending Order
Use reverse=True.
numbers = [3, 1, 2]
numbers.sort(reverse=True)
print(numbers)
Output
[3, 2, 1]
Sorting Text
Python sorts words in alphabetical order.
names = ["Tom", "Sara", "Ali"]
names.sort()
print(names)
Output
['Ali', 'Sara', 'Tom']
Using sorted()
sorted() creates a new sorted list.
The original data stays the same.
numbers = [5, 2, 4]
new_numbers = sorted(numbers)
print(numbers)
print(new_numbers)
Output
[5, 2, 4]
[2, 4, 5]
Sort by Length
Use key=len.
words = ["banana", "kiwi", "apple"]
words.sort(key=len)
print(words)
Output
['kiwi', 'apple', 'banana']
Sort List of Dictionaries
Sort by price.
products = [
{"name": "Book", "price": 10},
{"name": "Laptop", "price": 900},
{"name": "Pen", "price": 2}
]
products.sort(key=lambda item: item["price"])
for product in products:
print(product["name"], product["price"])
Output
Pen 2
Book 10
Laptop 900
Highest Score First
students = [
{"name": "Tom", "score": 85},
{"name": "Sara", "score": 92}
]
students.sort(
key=lambda item: item["score"],
reverse=True
)
for student in students:
print(student["name"], student["score"])
Output
Sara 92
Tom 85
Why Sorting Matters
Sorting helps users read data faster and find important values quickly.
Code Along
cities = ["Toronto", "Chicago", "New York"]
cities.sort()
print(cities)
Output
['Chicago', 'New York', 'Toronto']
Mini Challenge
Build a score sorter.
Steps:
- Create a list:
50, 90, 70, 30 - Print it sorted low to high
- Print it sorted high to low
Expected output:
[30, 50, 70, 90]
[90, 70, 50, 30]
Real World Use Case
Programs sort products by price, students by score, names alphabetically, and reports by date or value.
Quiz
- What does sorting mean?
- Which method changes the original list?
- What does
sorted()return? - What does
reverse=Truedo?
Assignment
Create a list of 5 cities. Sort them A to Z, then Z to A.
Summary
You learned how to sort numbers, text, and complex data using sort(), sorted(), and custom keys.