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

Code Challenge: Slice Function Task 4 Solution not accepted?

After searching on the forums, it appears that the reverse_evens() solution is as follows:

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

My question is - how is this different than the below: return items[-1::-2]

I tried submitting the second solution but it was not accepted. I've tried this in workspaces, and it seems that the output is the same with both even and odd-length lists. Is it related to the order of operations when reversing and traversing the list ? What am I missing?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The two functions don't alway give the same results. Examine the code below and its output:

# code
def reverse_evens_1(items):
    return items[-1::-2]

def reverse_evens_2(items):
    return items[::2][::-1]

print("reverse_evens_1([1, 2, 3, 4, 5]):")
print(reverse_evens_1([1, 2, 3, 4, 5]))

print("reverse_evens_2([1, 2, 3, 4, 5]):")
print(reverse_evens_2([1, 2, 3, 4, 5]))

print("reverse_evens_1([1, 2, 3, 4, 5, 6]):")
print(reverse_evens_1([1, 2, 3, 4, 5, 6]))

print("reverse_evens_2([1, 2, 3, 4, 5, 6]):")
print(reverse_evens_2([1, 2, 3, 4, 5, 6]))

#output
reverse_evens_1([1, 2, 3, 4, 5]):
[5, 3, 1]
reverse_evens_2([1, 2, 3, 4, 5]):
[5, 3, 1]
reverse_evens_1([1, 2, 3, 4, 5, 6]):
[6, 4, 2]
reverse_evens_2([1, 2, 3, 4, 5, 6]):
[5, 3, 1]

Notice that an even number of item produces an incorrect result in reverse_evens_1

The first solution starts at the last item and includes every other item moving toward the first item.

The second solution takes every other item start from the front of list then reverses it.

I see where I was wrong now, thank you !