'How to take a tuple as input, and return it as a new tuple, but only with odd numbers?

Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple'). I got 0.6/1 with this code:

def oddTuple(tup):
    b = 1
    if b % 2 != 0:
        d.append(tup[b])
        b += 1
    print (d)


Solution 1:[1]

You can do this with basic slicing.

tup = ('I', 'am', 'a', 'test', 'tuple')
tup[::2]
# ('I', 'a', 'tuple')

The syntax for slicing is iterable[start:end:step]. If you leave any of those start, end, or step blank, they default to the beginning, the end, and 1 respectively. So the above is going through the whole thing (beginning to end) but only selecting every other element.

If you need it in a method:

def odd_tuple(tup):
    return tup[::2]  # or print(tup) if you prefer

Solution 2:[2]

Try this:

def oddTuple(tup):
    return tuple(tup[i] for i in range(0, len(tup), 2))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Engineero
Solution 2 Riccardo Bucco