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

Task 4 reverse_evens doesn't work for me. Why?

I tried my code in a REPL and it works fine for the example input but when I check my work it says it returned the wrong value. What is the problem with reverse_evens? I don't know where to begin on how to fix it.

slices.py
def first_4(list):
    return list[:4]
def first_and_last_4(list):
    return list[:4] + list[-4:]
def odds(list):
    return list[1::2]

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

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

You're on the right track. However, you are not taking into account a list with an even number of items as opposed to a list with an odd number of items.

Hit: try reversing the whole list, then grab every other item.

Post back if you need more help. Good luck!!

I changed it to this and it works for both even and odd length lists. In my REPL it still works and I tried a bunch of test cases but the problem still says I don't return the correct values. What is my issue?

def reverse_evens(list):
    list.reverse()
    if(len(list) % 2 == 0):
        return list[1::2]
    else:
        return list[::2]
Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Matthew Barton, good question!! This had me stumped at first as your code appears to be written correctly.

The issue is the reverse() method changes the list in place. Since the list argument is mutable, the first time reverse_evens() is run, the argument itself is reversed, If run with the same argument again, the result changes:

def reverse_evens(list):
    list.reverse()
    if(len(list) % 2 == 0):
        return list[1::2]
    else:
        return list[::2]

l1 = [1,2,3,4,5]
l2 = [1,2,3,4,5,6]

print(l1, reverse_evens(l1))
print(l1, reverse_evens(l1))
print(l2, reverse_evens(l2))
print(l2, reverse_evens(l2))

# yields
[5, 4, 3, 2, 1] [5, 3, 1]
[1, 2, 3, 4, 5] [1, 3, 5]
[6, 5, 4, 3, 2, 1] [5, 3, 1]
[1, 2, 3, 4, 5, 6] [2, 4, 6]

One fix would be to make a local copy of the list argument before reversing.

I finally got it to work! Thank you for the help.

def reverse_evens(list):
    list = list.copy()
    list.reverse()
    if(len(list) % 2 == 0):
        return list[1::2]
    else:
        return list[::2]