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

Not sure what I'm doing wrong here. Shouldn't e[::-2] be reversing it and getting every other item?

I don't know what I'm messing up on here.

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

def first_and_last_4 (ok):
    skrt = ok[:4]
    reee = ok[-4:]
    return skrt+reee

def odds (ok):
    e = list(ok)
    return e[1::2]

def reverse_evens (ok):
    e = list(ok)
    return e[::-2]

2 Answers

Nicholas Reynolds
Nicholas Reynolds
7,613 Points

Hi Carter,

You are indeed reversing the item in the correct order, but I believe for the purposes of this code challenge it is unnecessary to put it in a list first.

def reverse_evens (ok):
    evens = ok[::2]
    return evens[::-1]

Hi Carter,

Nicholas' solution is the best and most straightforward. But, the reason his solution works, is because he works from the beginning of the list (i.e., his slice always starts with the even index of 0) and then reverses that answer.

But, just for academic purposes, if we want to make you slice work (starting from the end), we can't assume that the last index is always even. In the test case example ( [1,2,3,4,5}), the last element, 5, happens to be at an even index of 4. So, your code works and you believe it should work for all cases. However, try [1,2,3,4,5,6] instead and it fails.

To account for this "even/odd" scenario, I implemented a "start" variable which is either ultimately set to -1 or -2 depending on whether the iterable is odd or even in length.

def reverse_evens(iterable):
    start = 2 - (len(iterable) % 2)
    return iterable[-start::-2]