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

Why does this code does not work?

Hi, I eventually completed the slice functions challenge, but I'm curious as to why my first attempt was unfruitful.

Here it is:

 def reverse_evens(item):
    if len(item) % 2 == 0:
        reversed = item[-1::-2]
    else:
        reversed = item[-2::-2]
    return reversed

My idea was to check if the length of the iterable was odd or even to calibrate where I should start the slice. I played around in the IDLE and I guess it has something to do with the fact that when presented with a slice, my code count quotation marks as an element instead of ignoring it?

Thank you,

2 Answers

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.

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

( Taken from my reply here: https://teamtreehouse.com/community/reverseeven )

Hi Logan, My code actually takes this into account and check if the iterable length is odd or even. This is why I'm wondering why it doesn't work anyway

Hey Thieny,

The issue is that when you do [-2::-2], you start 2 indexes back. This cuts off the first entry in the array.

For example:

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

Sure, but Isn't the cut-off entry odd anyway, in this case?