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

jamie threadgold
jamie threadgold
925 Points

reverse_even returning incorrect value

Hi,

I have a problem with the last 'reverse_even' task. I'm getting the desired result in my compilier but not in the workspace..

Rgds, Jamie

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

def first_and_last_4 (meikejoosten):
    return meikejoosten[:4] + meikejoosten[-4:len(meikejoosten):1]

num = list(range(0,20))
def odds (num):
    return num[1::2]

num_two = list(range(0,21))
def reverse_evens (num_two):
    return num_two[-1::-2]

3 Answers

Hi Jamie,

Your code works fine if you run it with an iterable of odd length. If you have an even number of elements, it doesn't work. This is because you are reversing the iterable first, then taking alternate values. So,

[1, 2, 3, 4] # even length
[4, 3, 2, 1] # reversed first
[4, 2] # 'evens' & wrong

[0, 1, 2, 3, 4] # odd length
[4, 3, 2, 1, 0] # reversed first
[4, 2, 0] # reversed, & correct-by-fluke

# evens first, then reverse it:

[1, 2, 3, 4] 
[1, 3] # evens first
[3, 1] # reversed & correct

[0, 1, 2, 3, 4] 
[0, 2, 4] # evens
[4, 2, 0] # reversed & correct

Try something like this. I used a local variable to hold the evens list before reversing it. I'm sure it is possible to do this in one step; I'm equally sure that code won't be as readable.

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

I hope that makes sense.

Steve.

Christopher Shaw
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Shaw
Python Web Development Techdegree Graduate 58,248 Points

Your result will return the odds or evens, depending on the length of the list. So do it in two steps, first get a list of all the evens, then reverse the new list.

jamie threadgold
jamie threadgold
925 Points

Thank you both; it makes more sense now.

No problem! Always happy to try and help out. :+1: :smile: