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 trialPeter Falcone
Courses Plus Student 1,108 Pointsslices
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.
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])
3 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsThe 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
Courses Plus Student 1,108 PointsI used [-2::-2], [-2:0:-2], and several other methods, but for whatever reason it isn't working
Chris Freeman
Treehouse Moderator 68,441 PointsSee suggestions added to previous answer post.
Peter Falcone
Courses Plus Student 1,108 Pointsthanks. 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
Jeff Muday
Treehouse Moderator 28,720 PointsJeff Muday
Treehouse Moderator 28,720 PointsYour 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.