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

Koki Kira
Koki Kira
3,162 Points

reverse_even

I need help with the code for the function reverse_evens.

It's supposed to return a slice starting from the end of the iterable, but only for every value with an even index.

I feel dumb. Please send help.

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

def first_and_last_4(mylist):
    return mylist[0:4] + mylist[-4:]

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

def reverse_evens(mylist):
    return mylist[-1::-2]

1 Answer

Logan R
Logan R
22,989 Points

Hello!

So the meat of challenge 4 is: Return every item in the iterable with an even index...in reverse.

Given the list: [1, 2, 3, 4, 5], we want the following indexes: 0, 2, and 4. Our list would become [1, 3, 5]. Reversed, this is [5, 3, 1]. Your code works great for this example!

But what if our list is not an odd length. What if we had [1, 2, 3, 4, 5, 6] for example? We want the following indexes: 0, 2, and 4. Our list would become [1, 3, 5] then reversed to [5, 3, 1].

Here is where your code presents a problem.

>>> x = [1, 2, 3, 4, 5]
>>> y = [1, 2, 3, 4, 5, 6]

>>> x[-1::-2]
[5, 3, 1]
>>> y[-1::-2]
[6, 4, 2]

Your code starts at the last index, not at the last even index. In order to solve this, I would suggest separating it into 2 list commands (mylist[...][...]), one to get the even numbers and one to reverse the list.

I hope this helps! If you still don't understand anything, feel free to reply :)

Koki Kira
Koki Kira
3,162 Points

You blew my mind. I read the problem wrong.

I was thinking that the "-1" index in the list was ALWAYS an even index. (similar to '0' index always being an even index).

Thanks to you, I figured it out. Thank you!