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

Kabir Gandhiok
Kabir Gandhiok
12,553 Points

The last section of the challenge isn't passing, even though it passes when I check in the shell.

Hi,

The code challenge isnt clearing the last function reverse_evens, even though when I test it in the shell with exactly the same list as given in the example [1, 2, 3, 4, 5] in the challenge, I get the right output [5, 3, 1] yet the challenge isnt clearing it... I wonder why??

Thanks!

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

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

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

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

1 Answer

Kabir,

Since you don't know whether the last index (item[-1]) is an odd or even index, you must check the length of the item with len(item).

Here is my solution to the problem, compare this with your code to understand where you went wrong:

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

If you have any other questions I will update my answer, if you do not have any other questions:

Remember to upvote and to choose the best answer so that your question receives a checkmark in forums.

Kind regards,

Leo

Kabir Gandhiok
Kabir Gandhiok
12,553 Points

Thanks Leonard, I understand it now. If the list ends at odd index then my code doesnt quite work.

item = list(range(10)) item[-1::-2] gives [9, 7, 5, 3, 1] #this is what I was using in the challenge item[::2][::-1] gives [8, 6, 4, 2, 0]

hmm.. I see where I went wrong. Thanks for sharing your code, and the logic that it's unknown whether the list ends at odd or even index.

K

Glad I could help!