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
Python – Dual Tuple Alternate summation
When it is required to perform dual tuple alternate summation, a simple iteration and the modulus operator are used. This technique alternates between summing the first element of tuples at even indices and the second element of tuples at odd indices.
Below is a demonstration of the same ?
Example
my_list = [(24, 11), (45, 66), (53, 52), (77, 51), (31, 10)]
print("The list is :")
print(my_list)
my_result = 0
for index in range(len(my_list)):
if index % 2 == 0:
my_result += my_list[index][0]
else:
my_result += my_list[index][1]
print("The result is :")
print(my_result)
Output
The list is : [(24, 11), (45, 66), (53, 52), (77, 51), (31, 10)] The result is : 225
How It Works
The algorithm works as follows:
For even indices (0, 2, 4...), take the first element of each tuple
For odd indices (1, 3, 5...), take the second element of each tuple
Sum all selected elements together
In our example: 24 (index 0, first element) + 66 (index 1, second element) + 53 (index 2, first element) + 51 (index 3, second element) + 31 (index 4, first element) = 225
Alternative Approach Using Enumerate
my_list = [(24, 11), (45, 66), (53, 52), (77, 51), (31, 10)]
my_result = sum(tuple_item[0] if index % 2 == 0 else tuple_item[1]
for index, tuple_item in enumerate(my_list))
print("The result using enumerate:")
print(my_result)
The result using enumerate: 225
Conclusion
Dual tuple alternate summation uses the modulus operator to alternate between tuple elements based on index position. This technique is useful for processing paired data where you need to select different elements from each pair in an alternating pattern.
