Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,102 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
216,012 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.