Q:

Python program to get even indexed elements in tuple

belongs to collection: Python Tuple Programs

0

Example:

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

Getting Even Indexed Elements in Tuple

When we are working on python data structures. We might need to extract elements based on a specific pattern. in this program, we will be extracting an even index in the tuple.

Input:
(4, 1, 6, 8, 3)

Output:
(4, 6, 8)

To perform this task we simply need to traverse the tuple and get all the elements whose index is an even number. Python provides multiple methods to perform such tasks which can be easy and one of these methods might fit in the cases you required in your program in real-life programming.

All Answers

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

Method 1:

One method to solve the problem is by iterating on the tuple using generator expression and then use the enumerate() function in order to check the index for even values and then create a tuple from these values using tuple() method.

# Python program to get even indexed elements
# in Tuple 

# Creating and printing the tuple 
myTuple = (4, 1, 6, 8, 3)
print("Elements of the tuple are : " + str(myTuple))

# Getting even indexed elements in Tuple
evenTuple = tuple(values for i, values in enumerate(myTuple) if i % 2 == 0)

# Printing even indexed tuple
print("All even indexed elements of the tuple : " + str(evenTuple))

Output:

Elements of the tuple are : (4, 1, 6, 8, 3)
All even indexed elements of the tuple : (4, 6, 3)

Method 2:

Another method to solve the problem is by using recursion. We will be using a recursive function to extract even values from the tuples and return the values as a tuple.

# Python program to get even indexed elements 
# in Tuple 

# Recursive function 
def getEvenValTupleRec(myTuple):
    if len(myTuple) == 0 or len(myTuple) == 1:
        return ()
    return (myTuple[0], ) + getEvenValTupleRec(myTuple[2:])
    
# Creating and printing the tuple 
myTuple = (4, 1, 6, 8, 3, 7)
print("Elements of the tuple are : " + str(myTuple))

# Getting even indexed elements in Tuple
evenTuple = getEvenValTupleRec(myTuple)

# Printing even indexed tuple
print("All even indexed elements of the tuple : " + str(evenTuple))

Output:

Elements of the tuple are : (4, 1, 6, 8, 3, 7)
All even indexed elements of the tuple : (4, 6, 3)

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 program to remove space between tuple eleme... >>
<< Python program to perform row-wise element additio...