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

Peter Falcone
PLUS
Peter Falcone
Courses Plus Student 1,108 Points

slices

I've done everything correct so far, but I don't know what the problem is with my reverse_evens function. when I test the same exact thing in workspaces it works just fine.

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

def first_and_last_4(thing):
    return(thing[:4] + thing[-4:])

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

def reverse_evens(thing):
    return(thing[::-2])
Jeff Muday
Jeff Muday
Treehouse Moderator 27,510 Points

Your solution is close to being correct, but fails on odd sized lists.

Look at the answer here:

https://teamtreehouse.com/community/reverseeven-returning-incorrect-value

Basically, you need to FIRST get the even elements in the list, then reverse.

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,989 Points

The issue with simply taking every other item from the end of the using [::-2] is that when the list has an even number of items, this returns the index 5, 3, & 1. The trick is to divide the task into two parts:

  • gather the even-indexed items, try [::2]
  • reverse the above partial result, try [::-1]

This can be achieved with two slices. These slices can be cascaded ((a slice of a slice") on the same line.

Post back if you need more help. Good luck!!

Peter Falcone
PLUS
Peter Falcone
Courses Plus Student 1,108 Points

I used [-2::-2], [-2:0:-2], and several other methods, but for whatever reason it isn't working

Peter Falcone
PLUS
Peter Falcone
Courses Plus Student 1,108 Points

thanks. I get it now. [-2::-2] and [::-2] wouldn't work in all cases. but making the list, extracting the evens and then reversing will work no matter if the length of the original list is odd or even. with the previous examples, you would have to know that before hand