0

I have a problem with return even index in array.

def checkio(array):
if len(array):
    return ([i for i in array if array.index(i) % 2 == 0])
else:
    return 0

print (checkio([-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]))

and this code return

[-37, -19, 29, 3, -64, 36, 26, 55, -65]

but if i change '84' in my array for example for '74' its return

[-37, -19, 29, 3, -64, 36, 26, 55, 74, -65]

What the problem is it?

1 Answer 1

1

The issue is that 84 appears twice:

print (checkio([-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]))
                                               ^^                     ^^

However, array.index() returns the index of the first occurrence. This happens to be at an odd index so all occurrences of 84 get suppressed.

If you just want to take every other element, simply write array[::2]. This will take elements at indices 0, 2, 4, etc. No need to do any lookups.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.