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

Carlos Zuluaga
Carlos Zuluaga
21,184 Points

What's wrong in this code?

I've been struggling with this Code Challenge's task. Please refer to reverse_evens function.

I already checked the input and output on the Python Shell and it worked. But the Code Challenge Engine doesn't think the same.


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].


I appreciate your help guys!

slices.py
def first_4(iterable):
    return iterable[:4]

def first_and_last_4(iterable2):
    first4 = iterable2[:4]
    last4 = iterable2[-4:]
    first4.extend(last4)
    return first4

def odds(odd_list):
    return odd_list[1::2]

def reverse_evens(iterable3): # Here is the problem :/
    evens = iterable3[::-2]
    return evens
Carlos Zuluaga
Carlos Zuluaga
21,184 Points

I love Treehouse community!

3 Answers

Your code is halfway correct.

It's just that it only work with a list with the length even. If the list has an odd number or elements, the program will return all elements with odd indices reversed.


Check out my other answer for detail.

Steven Parker
Steven Parker
229,608 Points

Here's a few hints:

  • you need to be sure you return only the items with even indexes
  • you might calculate which item to start with based on the length of the iterable
  • another way would be to select even-indexed items with one slice, then use another slice to get the reverse
Sebastian Karg
Sebastian Karg
28,705 Points

Hi Carlos,

you are nearly there. I passed this challenge my self a few minutes ago.

To do so follow these hints:

Make sure your evens variable contain only items with even indexes
Do not only return your variable, reverse it also instead.