Related Articles

# Python – Get Even indexed elements in Tuple

• Last Updated : 10 Jul, 2020

Sometimes, while working with Python data, one can have a problem in which we need to perform the task of extracting just even indexed elements in tuples. This kind of problem is quite common and can have possible application in many domains such as day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = (1, 2, 4, 5, 6)
Output : (1, 4, 6)

Input : test_tuple = (1, 2, 4)
Output : (1, 4)

Method #1 : Using `tuple() + generator expression + enumerate()`
The combination of above functions can be used to solve this problem. In this, we perform task of iteration using generator expression, checking for even index using enumerate() and converting result to tuple using tuple().

 `# Python3 code to demonstrate working of ``# Extract Even indexed elements in Tuple``# Using tuple() + generator expression + enumerate()`` ` `# initializing tuples``test_tuple ``=` `(``5``, ``'Gfg'``, ``2``, ``8.8``, ``1.2``, ``'is'``)`` ` `# printing original tuple``print``(``"The original tuple : "` `+` `str``(test_tuple))`` ` `# Extract Even indexed elements in Tuple``# Using tuple() + generator expression + enumerate()``res ``=` `tuple``(ele ``for` `idx, ele ``in` `enumerate``(test_tuple) ``if` `idx ``%` `2` `=``=` `0``)`` ` `# printing result ``print``(``"The even indexed elements : "` `+` `str``(res))`
Output :

```The original tuple : (5, 'Gfg', 2, 8.8, 1.2, 'is')
The even indexed elements : (5, 2, 1.2)
```

Method #2 : Using recursion
This is yet another way in which this task can be performed. In this, we pass into recur. function the new list and extract the initial element and pass the list again till end of list, extracting just the even indexed element.

 `# Python3 code to demonstrate working of ``# Extract Even indexed elements in Tuple``# Using recursion`` ` `def` `helper_fnc(test_tuple):``    ``if` `len``(test_tuple) ``=``=` `0` `or` `len``(test_tuple) ``=``=` `1``:``        ``return` `()``    ``return` `(test_tuple[``0``], ) ``+` `helper_fnc(test_tuple[``2``:])`` ` `# initializing tuples``test_tuple ``=` `(``5``, ``'Gfg'``, ``2``, ``8.8``, ``1.2``, ``'is'``)`` ` `# printing original tuple``print``(``"The original tuple : "` `+` `str``(test_tuple))`` ` `# Extract Even indexed elements in Tuple``# Using recursion``res ``=` `helper_fnc(test_tuple)`` ` `# printing result ``print``(``"The even indexed elements : "` `+` `str``(res))`
Output :
```The original tuple : (5, 'Gfg', 2, 8.8, 1.2, 'is')
The even indexed elements : (5, 2, 1.2)
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up