
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Dual Tuple Alternate Summation
When it is required to perform dual tuple alternate summation, a simple iteration and the modulus operator are used.
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
Explanation
A list of tuple is defined and displayed on the console.
A variable is initialized to 0.
A list comprehension is used to iterate over the elements of the list, and modulus operator is used to check if remainder of every element divided with 2 is equal to 0.
If yes, the element in 0th index is added to the variable.
Otherwise, the element in first index is added to the variable.
This is the output that is displayed on the console.
Advertisements