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!

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

Daniel Mula Tarancón
.a{fill-rule:evenodd;}techdegree seal-36
Daniel Mula Tarancón
Data Analysis Techdegree Graduate 33,501 Points

I have to return every item in the iterable with an even index in reverse

I've created a variable called reverse in which I've put the iterable in reverse position. Afterwards I tried to extract the even items but it seems to be that it is wrong and I don't see why.

def first_4 (iterable):
    return iterable [:4]
def first_and_last_4 (iterable):
    return iterable [:4] + iterable [-4:]
def odds (iterable):
    return iterable [1::2]
def reverse_evens (iterable):
    reverse = iterable [::-1]
    return reverse [::2]

1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there! You're super close here, but it's the order in which you're doing this that is messing things up a bit. Let's say for example that our test data is actually [1, 2, 3, 4, 5, 6] instead of the one given. Your code first reverses that so you get [6, 5, 4, 3, 2, 1]. Then it takes a slice containing every other element which would result in [6, 4, 2]. But we want back the elements that were at even indexes when it started and in reverse. The result we should be getting is [5, 3, 1].

The solution here is to reverse the order you have things. First take every other element, which even starting with [1, 2, 3, 4, 5, 6] would be [1, 3, 5] and then reverse those. Your code actually works in half the cases. It works when the iterable has an odd number of elements. But reversing the order will work regardless of the number of elements in the list.

Hope this helps! :sparkles: