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

Enzie Riddle
.a{fill-rule:evenodd;}techdegree seal-36
Enzie Riddle
Front 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]

1 Answer

Jeff Muday
Jeff Muday
Treehouse Moderator 28,716 Points

Try this:

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

changed comment to answer