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

What am I doing wrong in this challenge task?

The last part of this challenge (defining reverse_evens) is returning a Bummer message. My answer works in python, and I’ve also tried defining reverse_evens(it) as return it[::-2], but neither are passing the challenge. What am I doing wrong?

This is the prompt: 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!

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

def first_and_last_4(it):
    new_value = it[0:4]+it[-4:]
    return new_value

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

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

1 Answer

This challenge is kinda weird because it wants you to take the even values from the list before you reverse it. The question doesn't make that super clear. So in your code, here you take the even values from the reversed list. This works when the list is an odd number, but it fails when the list is an even number (i.e. [1,2,3,4] should become [3,1] instead of [4,2]). Thus, this works:

def first_4(iterable):
    return iterable[:4]

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

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

def reverse_evens(iterable):
     iterable = iterable[::2]
     return iterable[::-1]

I see; that makes sense now. Thank you! :)