CodingNic

Data Structures

Sorting Data

Data Structures 26 min read

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.

python
numbers = [3, 1, 2]
numbers.sort()

print(numbers)

Output

text
[1, 2, 3]

Descending Order

Use reverse=True.

python
numbers = [3, 1, 2]
numbers.sort(reverse=True)

print(numbers)

Output

text
[3, 2, 1]

Sorting Text

Python sorts words in alphabetical order.

python
names = ["Tom", "Sara", "Ali"]
names.sort()

print(names)

Output

text
['Ali', 'Sara', 'Tom']

Using sorted()

sorted() creates a new sorted list.

The original data stays the same.

python
numbers = [5, 2, 4]

new_numbers = sorted(numbers)

print(numbers)
print(new_numbers)

Output

text
[5, 2, 4]
[2, 4, 5]

Sort by Length

Use key=len.

python
words = ["banana", "kiwi", "apple"]

words.sort(key=len)

print(words)

Output

text
['kiwi', 'apple', 'banana']

Sort List of Dictionaries

Sort by price.

python
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

text
Pen 2
Book 10
Laptop 900

Highest Score First

python
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

text
Sara 92
Tom 85

Why Sorting Matters

Sorting helps users read data faster and find important values quickly.

Code Along

python
cities = ["Toronto", "Chicago", "New York"]
cities.sort()

print(cities)

Output

text
['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:

text
[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

  1. What does sorting mean?
  2. Which method changes the original list?
  3. What does sorted() return?
  4. What does reverse=True do?

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.