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

Cameron Cottle
Cameron Cottle
13,742 Points

Python Slices :: Reverse Evens

I have tried a myriad of things to get this part to work properly in the code challenge and yet no matter what I do, it keeps on saying that something is wrong.

Reverse evens is supposed to take a list IE [1, 2, 3, 4, 5] and return [5, 3, 1].

I tested the code out, and it returns the expected value of [5, 3, 1], am I missing something?

Thank you for your help!

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

def first_and_last_4(list):
    first = first_4(list)
    second = list[-4:]
    return first + second

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

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

2 Answers

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

when you slice [::-2] you are starting at the end and going to the start by twos, but depending on whether the length of the list is an even number or not (and therefore whether the last index is an odd number or not), you may or may not slice the even indices. you can slice by twos from the start of the list, THEN reverse, or, to use [::-2], you will need to test for length and cut off the last element if it has an odd index (ie if the list length is even). then you would be starting your slice on an even index and be ok.

Cameron Cottle
Cameron Cottle
13,742 Points

You sir are absolutely correct, thank you so much!

YURI PAPINIAN
YURI PAPINIAN
11,838 Points

I also have tried to solve this problem a bunch of times. The thing is that the task is asking you to find all evens at the first place and then reverse them.

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