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

Lukas Johmann
Lukas Johmann
911 Points

What am I doing wrong in this challenge?

Hi treehousers, I have tried to solve this challenge but I cannot advance the last step. Anyone know why?

Challenge Task 4 of 4 You're on fire! Last one and it is, of course, the hardest.

Make a function named reverse_evens that accepts a single iterable as an argument. Return every item in the iterable with an even index...in reverse.

For example, with [1, 2, 3, 4, 5] as the input, the function would return [5, 3, 1].

You can do it!

slices.py
def first_4(iterable):
    return iterable [:4]
def first_and_last_4(itera):
    return itera [:4] + itera [-4:]
def odds(iterab):
    return iterab [1::2]
def reverse_evens(iterabl):
    return iterabl [-1::-2]

1 Answer

Ernestas Petruoka
Ernestas Petruoka
1,856 Points

First of all I want to apologise for my weak english (in case if I make some mistakes :) ). This challange is very tricky and the problem in your code is that you forgot that iterable can be either odd or even lenght long. The example is very tricky because if the iterable would be [1,2,3,4,5] like in example than your code would work, but iterable also could be for example [1,2,3,4,5,6] in which case your code would return [6,4,2] and indexes of them are 5,3,1 who ain't even so what you need to do is use if function to check iterable is even lenght long or odd lenght long.

My code looks like this:

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

Hope this would help you.