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

Chastin Davis
PLUS
Chastin Davis
Courses Plus Student 2,299 Points

I believe I need assistance on returning a reversed sliced list

I have return item[::-2] , in my method at the bottom of my code. I am still told this is wrong. The -2 moves me backward in the list and :: means I'm starting from one end and moving to the opposite end. I even try in workspace and I see that my method skips all odd indexes and returns the even indexes. What am I missing?

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

def first_and_last_4(item):
    return first_4(item) + item[-4:]

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

def reverse_evens(item):
    return item[::-2]

2 Answers

This one is tricky, because you need to actually do 2 things... get the even index, and then reverse them. I got hung up on this for a good minute, but I think it's because I didn't actually understand the full question. So, there are 2 ways to do this:

you can get the indexes first, store in a variable, and then reverse them:

item = item[::2] # get the items at even indexes
return item[::-1] # reverse them

or you can do a double slice

return item[::2][::-1]
Chastin Davis
Chastin Davis
Courses Plus Student 2,299 Points

Thanks. It is still unacceptable if return item[::-2] shows me as correct in workspace.. I'll apply your answer however.

[::-2] reverses everything stepping over every 2nd index from the last. It won't always get "even" indexes. If there are 6 things in a list for example, then it gets item[5], item[3], item[1].
you need to use [::2] instead, to get every even index starting at the beginning: item[0], item[2], item[4], and so on... then you just reverse it with [::-1]

hope that helps

I agree the example is a bit confusing: "For example, with [1, 2, 3, 4, 5] as the input, the function would return [5, 3, 1]." It should include " with [1, 2, 3, 4, 5, 6] as the input, the function would also return [5, 3, 1]."