Python Python Collections Slices Slice Functions

Pavel Agov
Pavel Agov
1,555 Points

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 53,521 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.

Pavel Agov
Pavel Agov
1,555 Points

I see where I was wrong now, thank you !