Python – Alternate Elements operation on Tuple

Sometimes, while working with Python Tuples, we can have problem in which we need to perform operations of extracted alternate chains of tuples. This kind of operation can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed.

Input : test_tuple = (5, 6, 3)
Output :
The alternate chain sum 1 : 6
The alternate chain sum 2 : 8

Input : test_tuple = (5, 6)
Output :
The alternate chain sum 1 : 6
The alternate chain sum 2 : 5

Method #1 : Using loop + enumerate()
The combination of above functions provide brute force solution to this problem. In this, we extract the elements along with indices using enumerate() and perform chaining using condition.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Alternate Elements operation on Tuple
# Using loop + enumerate()
  
# initializing tuple
test_tuple = (5, 6, 3, 6, 10, 34)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Alternate Elements operation on Tuple
# Using loop + enumerate()
sum1 = 0
sum2 = 0
for idx, ele in enumerate(test_tuple):
    if idx % 2:
        sum1 += ele
    else :
        sum2 += ele
  
# printing result 
print("The alternate chain sum 1 : " + str(sum1))
print("The alternate chain sum 2 : " + str(sum2)) 

chevron_right


Output :



The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 46
The alternate chain sum 2 : 18

 

Method #2 : Using list slicing
This problem can also be performed using slicing operations. In this, we perform the task of extracting alternate chains using list slicing technique.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Alternate Elements operation on Tuple
# Using list slicing
  
# initializing tuple
test_tuple = (5, 6, 3, 6, 10, 34)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Alternate Elements operation on Tuple
# Using list slicing
sum1 = sum(test_tuple[1::2])
sum2 = sum(test_tuple[0::2])
  
# printing result 
print("The alternate chain sum 1 : " + str(sum1))
print("The alternate chain sum 2 : " + str(sum2)) 

chevron_right


Output :

The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 46
The alternate chain sum 2 : 18



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.