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.
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.
Output:
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.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer