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
Selected Reading
Python – Find Product of Index Value and find the Summation
When working with lists in Python, you might need to calculate the product of each element with its position (index) and then find the sum of all these products. The enumerate() function is perfect for this task as it provides both the index and value during iteration.
Example
Below is a demonstration of finding the product of index value and summation ?
my_list = [71, 23, 53, 94, 85, 26, 0, 8]
print("The list is :")
print(my_list)
my_result = 0
for index, element in enumerate(my_list):
my_result += (index + 1) * element
print("The resultant sum is :")
print(my_result)
Output
The list is : [71, 23, 53, 94, 85, 26, 0, 8] The resultant sum is : 1297
How It Works
The calculation works as follows ?
- Position 0: (0 + 1) × 71 = 1 × 71 = 71
- Position 1: (1 + 1) × 23 = 2 × 23 = 46
- Position 2: (2 + 1) × 53 = 3 × 53 = 159
- Position 3: (3 + 1) × 94 = 4 × 94 = 376
- Position 4: (4 + 1) × 85 = 5 × 85 = 425
- Position 5: (5 + 1) × 26 = 6 × 26 = 156
- Position 6: (6 + 1) × 0 = 7 × 0 = 0
- Position 7: (7 + 1) × 8 = 8 × 8 = 64
Total sum: 71 + 46 + 159 + 376 + 425 + 156 + 0 + 64 = 1297
Alternative Using List Comprehension
You can achieve the same result using a more concise approach ?
my_list = [71, 23, 53, 94, 85, 26, 0, 8]
result = sum((index + 1) * element for index, element in enumerate(my_list))
print("The list is :")
print(my_list)
print("The resultant sum is :")
print(result)
The list is : [71, 23, 53, 94, 85, 26, 0, 8] The resultant sum is : 1297
Conclusion
Using enumerate() provides an elegant way to access both index and value simultaneously. This technique is useful for weighted calculations where position matters in the computation.
Advertisements
