Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Find the average of two list using Python?
Finding the average of two lists is a common task in data analysis and Python programming. Python provides several approaches including the statistics module, NumPy arrays, and basic arithmetic operations.
Using the statistics Module
The statistics.mean() function provides a straightforward way to calculate the average of combined lists ?
import statistics
# Initialize two lists
numbers_1 = [56, 34, 90]
numbers_2 = [23, 87, 65]
# Combine lists and find average using statistics.mean()
avg_of_lists = statistics.mean(numbers_1 + numbers_2)
print("Average of two lists:", avg_of_lists)
Average of two lists: 59.166666666666664
Using NumPy with Lambda Function
NumPy arrays combined with lambda functions allow element-wise operations for finding averages ?
import numpy as np
# Initialize two lists
numbers_1 = [56, 34, 90]
numbers_2 = [23, 87, 65]
# Use lambda function to find element-wise average, then overall mean
element_averages = list(map(lambda a, b: (a + b) / 2, numbers_1, numbers_2))
overall_average = np.mean(element_averages)
print("Element-wise averages:", element_averages)
print("Overall average:", overall_average)
Element-wise averages: [39.5, 60.5, 77.5] Overall average: 59.166666666666664
Using Basic Python Functions
The most straightforward approach uses built-in sum() and len() functions ?
# Initialize two lists
numbers_1 = [56, 34, 90]
numbers_2 = [23, 87, 65]
# Calculate average using sum() and len()
total_sum = sum(numbers_1) + sum(numbers_2)
total_length = len(numbers_1) + len(numbers_2)
avg_of_lists = total_sum / total_length
print("Average of two lists:", avg_of_lists)
Average of two lists: 59.166666666666664
Comparison of Methods
| Method | Best For | Advantages |
|---|---|---|
statistics.mean() |
Simple calculations | Built-in, readable |
| NumPy with lambda | Element-wise operations | Flexible, powerful |
sum() and len()
|
Basic requirements | No imports needed |
Conclusion
Use statistics.mean() for simple average calculations, NumPy for complex data operations, and basic functions when avoiding external dependencies. All methods produce identical results for finding the average of two lists.
