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

Vladimir Lapcevic
Vladimir Lapcevic
6,363 Points

Why even function does not work?

Please review my code and explain why my fourth function does not work properly. Thanks

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

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

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

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

3 Answers

Ty Yamaguchi
Ty Yamaguchi
25,397 Points

You could try something like this:

def reverse_evens(som):
    evens = som[::2]
    return evens[::-1]
Steven Parker
Steven Parker
229,732 Points

:warning: Posting explicit solutions without explanations is strongly discouraged by Treehouse, and may be subject to redaction by staff or moderators.

Steven Parker
Steven Parker
229,732 Points

Your function will work, half of the time. But depending on the length (actually the even/odd-ness) of the list, it might return reverse odds instead.

To guarantee reverse evens, there's two basic strategies:

  • use the length of the list to compute the "start" index
  • extract the evens first, then reverse them in a separate operation (slice)

Either method will work when properly implemented. (hint: the second one might be easier to do)