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

 Live Demo

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.

Updated on: 2021-09-06T09:13:39+05:30

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements