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

I can't find the answer in reverse_evens

I don't know what is wrong with my code for reverse evens.

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

def first_and_last_4(items):
      return items[0:4] + items[-4:]

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

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

1 Answer

Hey Michael! Couple of things here, one being that your starting at the index value -1, which is the last item, and you trying to skip 2 ahead after, but your gonna want to go two backwards to get thru the list. Secondly your code only works if the length of the list is odd. This is because if the length of the list is even, then the final index value will be odd and so you will get every odd index. To resolve this you should add some conditions in your function to check if the list is even or odd, you could do it like this:

def reverse_evens(items):
    if len(items) % 2:
        return items[-1::-2]
    else:
        del items[-1]
        return items[-1::-2]

So were checking if the length of is even, if so we do what you tried to do (keeping in mind that we want to go backwards), if its even then we remove the last item and do the same (so that the list is even). Hope this helps!

I figured it out, I did it a little different but quite similar.

if len(items) %2 != 0: return items[-1::-2] else: return items[-2::-2]

Yup that totally works aswell, good job on figuring it out yourself! You can still mark the question as "solved" by sellecting a "best answer".