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

Kate Bishop
Kate Bishop
1,410 Points

Im not sure why this isnt working when i run it on a seperate python runner it gives me the result you are looking for

Im not sure why this isnt working when i run it on a seperate python runner it gives me the result you are looking for

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

def first_and_last_4(list_1):
    new_list = []
    new_list += list_1[0:4]
    new_list += list_1[-4:]
    return new_list

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

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

1 Answer

AJ Salmon
AJ Salmon
5,675 Points

Hey Kate, the issue here is that if your iterable ends in an odd index, it will start the negative step on an odd index, which will then skip over all of the even ones and return only the odds. Here's what ha[pens with your code:

>>> reverse_evens([0, 1, 2, 3, 4, 5, 6, 7, 8])
[8, 6, 4, 2, 0]
# here it returns the correct output, items with an even index, reversed
>>> reverse_evens([0, 1, 2, 3, 4, 5, 6, 7])
[7, 5, 3, 1]
# here, because it ends with an odd index, it only returns the items with an odd index

To fix this, try assigning a variable to list_1[::2] to first make sure you have all of the even indexed items in the iterable, then reversing it with just a single negative step. Happy coding! :)