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

Azher Hussaini
Azher Hussaini
3,178 Points

Is Reverse_evens challenge bugged?

I've tried the below block of code, but I can't seem to pass the challenge. As I understand it, I'm to get the indexes from the end of the list.

For example, if the list is [1,2,3,4,5,6] then the result should be [6,4,2] and for [1,2,3,4,5] it should be [5,3,1].

Would really appreciate some help on this!

slices.py
#def first_4(item):
    #return item[:4]
#def first_and_last_4(item):
    #return (item[:4] + item[-4:])
#def odds(item):
    #return item[1::2]
def reverse_evens(item):
    if len(item)%2 != 0:
        return item[::-2]
    else:
        list = item[::-1]
        return list[::2]
Dave StSomeWhere
Dave StSomeWhere
19,870 Points

You should get the same result of [5, 3, 1] for both [1, 2, 3, 4, 5] and [1, 2, 3, 4, 5, 6] - so that's what you need to fix.

The challenge is:

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].

So, the example [1, 2, 3, 4, 5] has entries where

1 is index 0 - even
2 is index 1 - odd
3 is index 2 - even
4 is index 3 - odd
5 is index 4 - even
6 would be index 5 - odd - don't include

that's why the function would return [5, 3, 1] - it would be the same result adding the 6 since it's index is 5 and odd.

1 Answer

Steven Parker
Steven Parker
229,644 Points

There's a bit more to this challenge than there might seem at first glance. Getting the right output for all input cases will require one of these two strategies:

  • compute the starting position based on the length (or even/odd-ness) of the list
  • extract the even indexed values first, and then reverse them in a separate step

It looks like you already had the right idea, and were implementing the first strategy. But after the test, either branch will need only one slice. The only difference in the slices should be the start value.

Azher Hussaini
Azher Hussaini
3,178 Points

Thank you both! Was able to solve :)