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

jacobtydings
jacobtydings
4,262 Points

Having trouble with negative_evens

Hey, I seem to be having some trouble getting it to accept the code I wrote for the last function. I don't see why returning the list at [::-2] wouldn't work, as it seems to anywhere else I go. The slicing of the iterable is just there so that I don't throw things off in the workspace, and I think for the sake of the challenge, it's optional. What am I doing wrong?

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

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

def odds(iterable):
    iterable = iterable[1::2]
    return iterable

def reverse_evens(list1):
    list1 = list1[:]
    list2 = list1[::-2]
    return list2

1 Answer

Steven Parker
Steven Parker
231,269 Points

A slice with a step of -2 will actually work half the time, based on the length of the list. The other half of the time it will return the odd indexed items reversed instead of the evens.

To work properly every time, there's two basic strategies:

  • use the length (actually even/odd-ness) of the list to determine the starting position
  • extract the even indexed items first and then reverse them in a separate operation

Hint: Either strategy is effective, but the second one might be easier to implement.