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

It seems that reverse_evens question has an issue, I have tried my answer in the local env and it is working.

I have tried to create a list as in the example
>>>item_list = [1,2,3,4,5] .

Then I tried my code .

>>>item_list[-1::-2] .

And the result was as provided in the example .

>>>[5, 3, 1] .

but after I click the "check work" button it always says "Didn't get the right values from reverse_evens .

Has anyone got stuck in the same situation?

def first_4(item_list):
    return item_list[:4]

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

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

def reverse_evens(item_list):
    return item_list[-1::-2]

1 Answer

Steven Parker
Steven Parker
229,644 Points

This method will work, but only in half of the cases, based on the list length. To create a method that will work with any size list, there's two common strategies:

  • compute the starting position based on the length of the list
  • take the even-indexed items first, and then reverse them with another slice

Hint: Either method will work when correctly implemented, but the second one might be a bit easier.

Thanks Steven!
I finally solved it by adding new method to calculate the start point like this:

def calculate_start_point(item_list):  
     if(len(item_list) % 2 == 0):
         return -2
         return -1

And then I changed the reverse_evens method to be like this:

def reverse_evens(item_list):  
    return item_list[calculate_start_point(item_list)::-2]  

I can also fix it inline like this:

item_list[-2 if len(item_list)%2 == 0 else -1::-2]
Steven Parker
Steven Parker
229,644 Points

Good job! And since the spoilers are already "out of the bag", that alternative strategy looks like this:

    return item_list[::2][::-1]