Q:

Python program to alternate elements operation on tuple

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Performing alternate elements operation on tuple

We have a tuple consisting of multiple elements and we need to perform an operation on alternate elements of the tuple i.e. operations will consider either even or odd values of the tuple for one iteration.

For performing this task we will be traversing the tuple and then performing operations on alternate elements of the tuple.

Python programming language provides multiple methods to solve the problem. Here, we will be discussing some of them.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method is to simply loop over the tuple and find the elements that have an alternate occurrence index. For this, we will be using the enumerate() method and then alternate the elements using the conditional operator.

# Python program to Alternate Elements Operation
# on Tuple

# Creating and printing tuple list 
myTuple = (3, 1, 6, 4, 9)
print("Initial values of tuple : " + str(myTuple))

# Performing alternate element operation
sumEven = 0
sumOdd = 0
for idx, value in enumerate(myTuple):
	if idx % 2:
		sumEven += value
	else :
		sumOdd += value

# Printing alternate elements operation 
print("The alternate elements sum for even index values : " + str(sumEven))
print("The alternate elements sum for odd index values : " + str(sumOdd))

Output:

Initial values of tuple : (3, 1, 6, 4, 9)
The alternate elements sum for even index values : 5
The alternate elements sum for odd index values : 18

Method 2:

Another method to solve the problem is by using the slice operator which will extract the elements of the tuple from the required alternate index.

# Python program to Alternate Elements Operation
# on Tuple

# Creating and printing tuple list 
myTuple = (3, 1, 6, 4, 9)
print("Initial values of tuple : " + str(myTuple))

# Performing alternate element operation
sumOdd = sum(myTuple[1::2])
sumEven = sum(myTuple[0::2])
  
# Printing alternate elements operation 
print("The alternate elements sum for even index values : " + str(sumEven))
print("The alternate elements sum for odd index values : " + str(sumOdd))

Output:

Initial values of tuple : (3, 1, 6, 4, 9)
The alternate elements sum for even index values : 18
The alternate elements sum for odd index values : 5

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Convert Tuple to Tuple Pair... >>
<< Python program to print all group tuples by Kth in...