beginner

Sum of List Elements

Learn how to calculate the sum of all elements in a Python list.

Practice the fundamental skill of iterating through a list and accumulating values.

📚 Concepts & Theory

Working with Lists

Lists store multiple items:

nums = [1, 2, 3]
for n in nums:
    print(n)

🎯 Your Challenge

Write a function sum_list that returns the sum of all numbers in a list.

📝 Starter Code

Python
def sum_list(numbers):
    pass

print(sum_list([1, 2, 3, 4, 5]))

Solution

Python
def sum_list(numbers):
    total = 0
    for num in numbers:
        total += num
    return total

print(sum_list([1, 2, 3, 4, 5]))

Explanation

We use an accumulator pattern.

❓ Frequently Asked Questions

Use a loop or sum()

🔗 Related Concepts