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

why can't I jump one step in the reverse slice?

Hi guys I've done some research and I think my reverse_evens() function is ok, why doesn't it work?

thanks

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

def first_and_last_4(ite):

    head = ite[:4]
    tail = ite[-4:]

    concat = head + tail
    return concat

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

def reverse_evens(iterable):
    return iterable[::-2]

1 Answer

Steven Parker
Steven Parker
220,415 Points

You're not accounting for the possibility of different list lengths.

This approach will only work on lists that have an odd number of items. If the list passed to the function has an even number of items, this will return reverse odds instead of reverse evens.

You'll either need to calculate the starting position based on the list size, or you'll need to extract the evens first and then reverse them in a separate step.

hey steven thank you for the tips, but shouldn't there be a way to present a reverse list, and jump one step, without removing the evens?

And I have no ideia how to calculate the staring position, and how can I use that to return the reverse evens

Steven Parker
Steven Parker
220,415 Points

If the list had an even number of items, you'd need to start at the second-to-last item (instead of the very last item) to get the even-numbered indexes ("iterable[-2::-2]").