Finding the sum of elements in a list is a common operation used in many programs.
Example:
[1, 2, 3, 4, 5] → Sum = 15
Let’s explore different ways to calculate the sum π
πΉ Method 1 – Using sum() Function
numbers = [1, 2, 3, 4, 5]
print("Sum:", sum(numbers))
✅ Easiest and most recommended method.
πΉ Method 2 – Using for Loop
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("Sum:", total)
✅ Good for understanding logic.
πΉ Method 3 – Taking User Input
numbers = list(map(int, input("Enter numbers: ").split()))
print("Sum:", sum(numbers))
✅ Dynamic input from user.πΉ Method 4 – Using while Loop
numbers = [1, 2, 3, 4, 5] i = 0 total = 0 while i < len(numbers): total += numbers[i] i += 1 print("Sum:", total)
✅ Alternative looping method.
πΉ Method 5 – Using functools.reduce()
from functools import reduce numbers = [1, 2, 3, 4, 5] total = reduce(lambda x, y: x + y, numbers) print("Sum:", total)
✅ Functional programming approach.
πΉ Output
Sum: 15
π₯ Key Takeaways
✔️ sum() is the simplest and fastest
✔️ Loops help build understanding
✔️ reduce() is useful for functional style
✔️ Handle empty lists in real-world use


0 Comments:
Post a Comment