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

Marius Zlota
Marius Zlota
8,265 Points

Reverse_evens doesn't parse. It does in Workspaces

What's not right? Also tried a[-1::-2] - same result

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

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

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

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

2 Answers

Stuart Wright
Stuart Wright
41,120 Points

Notice that your solution will not do as the question asks if you happen to give it a list with an even number of elements.

For example if a = [1, 2, 3, 4, 5, 6]

Your code will return [6, 4, 2].

Those elements are at index 5, 3, 1 (odd).

I'm not actually sure if there's a way to solve this with one single slice statement (there might well be), but you can solve this by first getting all elements with an even index, then performing a second step to reverse those elements.

Steven Parker
Steven Parker
231,269 Points

You can't do this with only a step because the iterable length may be even or odd.

So you either need to compute the start value using the length of the iterable, or you need one slice to get the even indexes and another to reverse them.

:warning: Be careful about testing a challenge in an external REPL.
If you have misunderstood the challenge, it's also very likely that you will misinterpret the results.