Finding the average (mean) of a list means adding all elements and dividing by the total number of elements.
Formula:
Average = Sum of elements / Number of elements
Example:
[2, 4, 6, 8] → Average = (2+4+6+8)/4 = 5.0
Let’s explore different ways to calculate average π
πΉ Method 1 – Using sum() and len()
✅ Easiest and most recommended method.
✅ Easiest and most recommended method.
πΉ Method 2 – Using for Loop
numbers = [2, 4, 6, 8] total = 0 for num in numbers: total += num avg = total / len(numbers) print("Average:", avg)✅ Good for understanding logic.πΉ Method 3 – Taking User Input
numbers = list(map(int, input("Enter numbers: ").split())) avg = sum(numbers) / len(numbers) print("Average:", avg)✅ Dynamic input from user.
πΉ Method 4 – Using while Loop
numbers = [2, 4, 6, 8] i = 0 total = 0 while i < len(numbers): total += numbers[i] i += 1 avg = total / len(numbers) print("Average:", avg)
✅ Alternative looping method.
πΉ Method 5 – Using Function
def average(lst): return sum(lst) / len(lst) print(average([2, 4, 6, 8]))
✅ Clean and reusable.
πΉ Output
Average: 5.0
π₯ Key Takeaways
✔️ Use sum() and len() for simplicity
✔️ Average = total / count
✔️ Loops help build logic
✔️ Handle empty list to avoid division error


0 Comments:
Post a Comment