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

why does this not work?: def reverse_evens(arg): return arg[::-2]

Please help!

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

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

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

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

in the reverse_evans, you should the return to arg[::-1] rather than arg[::-2]

3 Answers

Hi Hwang Ju,

Doing a step of -2 is only going to work for certain lists. The problem is that you don't know if the last item is an even or an odd index.

See the following output:

>>> [1, 2, 3, 4, 5][::-2]
[5, 3, 1]
>>> [1, 2, 3, 4][::-2]
[4, 2]
>>>

It works out for the given example because the 5 is at index 4 and you end up getting indexes 4, 2, 0

The second example doesn't work because the 4 is at index 3 and you end up getting indexes 3, 1

I don't know if it's possible to do this in one slice without additional logic. I solved it with 2 slices.

The first slice gets the even indexes and then a slice on that to reverse it.

arg[::2][::-1]

Thank you very much! Happy holidays!

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]. You can do it!

That was the question asked. -1 is incorrect

oh i though you were on another quiz, my bad. i tried to run the code on mt terminal and it ran with no problem. I also tried redoing the quiz with your code and it passed with no problem, maybe its an internet connection problem ???