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

Couldn't get pass Challenge Task 4 of 4. (reverse_evens)

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

print(reverse_evens([1,2,3,4,5]))

[5,3,1] Verified it in workspace but it keeps saying its not correct. Not sure what is missing.

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

def first_and_last_4(iterable_item):
    my_list = iterable_item[:4]
    my_list.extend(iterable_item[-4:])
    return my_list

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

def reverse_evens(iterable_item):
    return iterable_item[::-2]
Todd Costa
Todd Costa
3,380 Points

I'm stuck on the same exact task, i believe the issue that you're running into (which i did too) is if the list ends with an odd index number. ie lets say the last iterable_item is index 21, they want only the even indexs so your would need to disregard the very last item. Please post if you figure it out, i'm not making any headway.

2 Answers

Todd Costa
Todd Costa
3,380 Points

Sorry for the double post but writing my response to you helped me think it through.

First get the even indexs iter = iter[::2] Then reverse it return iter[::-1]

Leon Silcott
Leon Silcott
27,390 Points

For anyone's future reference, I solved this by using doing the following:

def reverse_evens(given):
    #Check to see whether list is odd length or even 
    if len(given) % 2 != 0:
        # If list is odd start from the first last index and iterate -2 (will always be odd)
        given = given[-1::-2]
    else:
        # If list is even start from the second to last index (now odd index) and iterate -2
        given = given[-2::-2]
    # Return the newly generated given list
    return given

Hope it helps!