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

I don't understand why this code is incorrect?

Hello, could someone please help me understand you this is this code is incorrect? It works fine when i test it but for some reason when i use it to answer the quiz i get "Didn't get the expected answer"

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

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

def first_and_last_4(item):
    return (item[:4]) + (item[-4:])

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

def reverse_evens(item):
    return item[::-2]
Dave StSomeWhere
Dave StSomeWhere
19,870 Points

You code is incorrect because you only return the values with even indexes when there is an odd number of values.

Their example of [1, 2, 3, 4, 5] works just fine and you get [5, 3, 1] the desired result

But, if the list is [1, 2, 3, 4, 5, 6] you code produces [6, 4, 2] giving the odd index values.

So, you need to determine if there are an even or odd number of values in the list and adjust appropriately.

@Dave StSomeWhere , Good point!!!

Oh thank you @Dave StSomeWhere , somehow I don't think I fully thought this one through. All is working now. I appreciate the help.

1 Answer

This is another way, but the better way to do it is you want to pick out all the even index items then reverse the order. I am not a pro, but I will try my best.

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

# A break down version
def reverse_evens(item):
    # Picking out all the even index item assign it to even
    even = item[::2]
    # Takes all the even index item then reverse the order and assign it to reverse_order
    reverse_order = even[::-1]
    return reverse_order