In this challenge, you’ll write a function that calculates the sum of all numbers in a list. The math is simple—but the real goal is handling edge cases and writing code that behaves predictably.
Your Task
Write a function that accepts a list of numbers and returns their total sum.
Function Signature
def sum_numbers(numbers: list) -> int | float:
…
Rules
- The input must be a list.
- Every element in the list must be a number (
intorfloat). - If the list is empty, return
0. - If the input is invalid, raise a
TypeError.
Examples
sum_numbers([1, 2, 3]) → 6
sum_numbers([1.5, 2.5]) → 4.0
sum_numbers([-1, 5, -2]) → 2
sum_numbers([]) → 0
Invalid Input Examples
sum_numbers("123") → TypeError
sum_numbers([1, "2", 3]) → TypeError
sum_numbers(None) → TypeError
Hints (Optional)
- Start by validating the input before doing any math.
- You can use a loop or Python’s built-in tools—but make sure your behavior matches the rules.
- Think about how you want your function to fail when input is wrong.


What These Tests Cover
✔️ Valid integer and float lists
✔️ Empty list behavior
✔️ Negative numbers
✔️ Single-item lists
✔️ Non-list input validation
✔️ Mixed-type list rejection
This keeps the challenge:
- Predictable
- Defensive
- Beginner-friendly but correct
What This Challenge Teaches
- Iterating over lists
- Accumulators (
total += n) - Input validation
- Defensive programming
- Writing predictable return values
Bonus Challenges
- Ignore non-numeric values instead of raising an error
- Support nested lists
- Compare your solution with Python’s built-in
sum()
Why This Matters
Real-world data is rarely clean. Writing functions that fail clearly or handle edge cases gracefully is just as important as getting the correct result.
Encouring again you to take some extra time to check the test code. I’ll be using this more in the coming challenges.
🔗 View reference solution on GitHub
(After you’ve tried the challenge)
👉 Next Challenge → Remove Duplicates from a List
Want more practical Python challenges?
Subscribe to the Solve With Python newsletter and get new problems delivered to your inbox.