computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

📊

🎓

⏱ 30 min

Free

Data Crunching

Sort, filter and summarize data with list comprehensions, sorted(), sum() and friends.

🎯 What you will learn

  • Write list comprehensions
  • Sort and filter data
  • Calculate averages, max and min

👋 Let’s get started!

Data scientists turn piles of numbers into answers 📊. Who scored highest? What’s the average? Python makes it fast — often in just one line.

🪜 Step by step

1. ⚡ List comprehensions

Build a new list in one line: [expression for item in list if condition]

nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
squares = [n * n for n in nums]
print(evens, squares)
2. 🔃 Sorting

sorted() returns a sorted copy. key= chooses what to sort by.

players = [("Ana", 88), ("Ben", 95), ("Cho", 72)]
ranked = sorted(players, key=lambda p: p[1], reverse=True)
print(ranked[0])
3. 🧮 Summaries

sum(), max(), min() and len() answer big questions.

temps = [70, 75, 68, 80, 77]
print("Average:", sum(temps) / len(temps))
print("Hottest:", max(temps))

🧪 Try it!

Change the code and press ▶ Run to see what happens. You can’t break anything!

Class survey analyzer

answers = ["pizza", "tacos", "pizza", "sushi", "pizza", "tacos"]
counts = {}
for food in answers:
    counts[food] = counts.get(food, 0) + 1

for food, n in sorted(counts.items(), key=lambda x: x[1], reverse=True):
    print(f"{food:<6} {'█' * n} {n}")

Top score

scores = [42, 97, 65]
best = max(scores)
print("Best:", best)

📖 Key words

Tap a card to flip it over!

List comprehension
A one-line list builder ⚡
sorted()
Returns a sorted copy 🔃
lambda
A tiny unnamed function λ
Average
Sum divided by count ➗

🏆 Challenge

Print a list of the names of everyone who scored 80 or more, in the original order.

Challenge

results = [("Ana", 88), ("Ben", 95), ("Cho", 72)]

Knowledge Check Quiz

  1. What prints?
  2. What does sorted(x, reverse=True) do?
  3. What prints?
← Previous lesson
Next lesson →