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

Daniel Mula Tarancón
seal-mask
.a{fill-rule:evenodd;}techdegree
Daniel Mula Tarancón
Python Development Techdegree Student 16,031 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.

slices.py
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
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
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: