Welcome to the Treehouse Community
Looking to learn something new?
Enzie RiddleFront End Web Development Techdegree Graduate 19,278 Points
Slices and Backwards Lists
Here's the question:
You're on fire! Last one and it is, of course, the hardest. Make a function named reverse_evens that accepts a single iterable as an argument. Return every item in the iterable with an even index...in reverse. For example, with [1, 2, 3, 4, 5] as the input, the function would return [5, 3, 1]. You can do it!
What am I doing wrong? PLEASE explain step-by-step, I am new to this!
def first_4(items): for iterables in items: return items[0:4] def first_and_last_4(single_iterable): return single_iterable[0:4] + single_iterable[-4:] def odds(index): return index[1::2] def reverse_evens(single_iterable_2): for every_item in single_iterable_2: return single_iterable_2[-1:0:-2]
Jeff MudayTreehouse Moderator 27,510 Points
def reverse_evens(array): return array[0::2][-1::-1]
The first bracketed part gets only the even elements, the last square brackets simply reverses that list.
Below, I do two steps, and explain it a little better with comments.
def reverse_evens(items): even_items = items[0::2] # start at zero, go to end, using steps of 2 reverse_even_items = even_items[-1::-1] # start at last element, go backwards using steps of -1 return reverse_even_items