Mutua Ndunda
Mutua Ndunda

Reputation: 11

Python Indexing Tuples

I am creating a function, this function when applied to a tuple it should return the even indexed element in the tuple. How comes it's not returning the fourth indexed element?

def oddTuples(aTup):
    '''
    aTup: a tuple

    returns: tuple, every other element of aTup. 
    '''
    evenIndex = ()
    evenTuple = ()
    for i in aTup:
        if aTup.index(i)%2 == 0:
            evenIndex = evenIndex +  (aTup.index(i),)
            evenTuple += (aTup[aTup.index(i)],)
    return evenTuple

Upvotes: 1

Views: 463

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78546

Using a.index will return the index of the first occurrence of the item. You can't really count on that when the items in your tuple are not unique.

You should consider using enumerate instead:

for i, v in enumerate(aTup):
    if i % 2 == 0:
        ...

You can better still use slicing and be less verbose:

aTup[::2] # starts at zero, stops at the length of the tuple, steps in 2s

Also, keep in mind that indexing starts from 0 by default. But with enumerate you can make it start from a selected number:

for i, v in enumerate(aTup, 1) # starts counting from 1

Upvotes: 4

Vlade
Vlade

Reputation: 99

works fine for me. Tuples start indexes at 0. So if you have tuple:

(0,1,2,3,4,5,6)

it returns

(0, 2, 4, 6)

If you want 4th, youll need to change

if i % 2 == 0:

into

if i % 2 == 1:

Upvotes: 0

Related Questions