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

Get an error, while the code works just in Python IDLE

HI everyone, I'm workin on the following challenge:

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].

I use the following code:

def reverse_events(answer): return(answer[::-2])

De code works just fine in Python IDLE or Workspaces, but I keep getting the following error: Didn't get the right values from reverse_evens.

What am I doing wrong here?

Thank you for you help.

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

def first_and_last_4(answer):
    first_4 = answer[:4]
    last_4 = answer[len(answer)-4:]
    return(first_4 + last_4)

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

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

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hi Sameer,

While the code will work with an odd numbered list (eg. [1, 2, 3, 4, 5]), if you try the code with an even numbered list (eg [1, 2, 3, 4, 5, 6], the code will not return the correct values, even in IDLE.

Hint: you will need to check the length of the list before applying the slice, and adjust it depending on whether it is an even numbered or an odd numbered list.

Nice work so far! :thumbsup:

Keep Coding! :) :dizzy:

Thank you for respons.

I've been working on it for a hour, and drove me crazy. I came up with this and it worked:

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

Thank you!