Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Slices Slice Functions

Enzie Riddle
seal-mask
.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!

slices.py
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
MOD
Jeff Muday
Treehouse Moderator 27,510 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