Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Slices Slice Functions

Task 4/4, function works when tested on python shell but isn't accepted as a correct answer to pass the challenge

''' def reverse_evens(iterable): return iterable[::-2] ''' This functions returns [5, 3, 1] when passed the example [1, 2, 3, 4, 5] in python shell but isn't accepted on the challenge page. Therefore I cannot determine where the mistake is. Can someone see where the mistake might be?

slices.py
def first_4(iterable):
    return iterable[:4]

def first_and_last_4(iterable):
    return iterable[:4] + iterable[-4:]

def odds(iterable):
    return iterable[1::2]

def reverse_evens(iterable):
    return iterable[::-2]

1 Answer

The problem is that your code (iterable[::-2]) only works when the length of the iterable is odd.

The first thing comes to me is using a conditional:

def reverse_evens(iterable):
    return iterable[-2::-2] if len(iterable) % 2 == 0 else iterable[::-2]

or if you prefer:

def reverse_evens(iterable):
    if len(iterable) % 2 == 0:
        return iterable[-2::-2]
    else:
        return iterable[::-2]

Just for fun, the solution can be even shorter:

def reverse_evens(iterable):
    return iterable[::-2] if len(iterable) % 2 else iterable[-2::-2]

Ohh I hadn't thought about this! I wasn't testing it enough. Thanks!

No problem! If the answer is helpful, a "Best Answer" would be appreciated. Good luck on learning!

Although this was not posted by me but I really benefited from the insight and hints. Thank you Kip.

I'm glad it helped!