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 trialAlbert Tomasura
11,041 PointsSlice Functions
For this challenge I completed 3 out 4 steps with ease. I started running into constant errors/incorrect values messages with the last portion (reverse_evens). I ran the same code through Workspaces with no errors and when I adjusted the code to print instead of return, using the example provided ([1, 2, 3, 4, 5]). The result was [5, 3, 1] which was the intended answer according to the example.
def first_4(ok):
return ok[0:4]
def first_and_last_4(ok):
return ok[0:4] + ok[-4:]
def odds(ok):
return ok[1::2]
def reverse_evens(ok):
return ok[-1::-2]
2 Answers
james south
Front End Web Development Techdegree Graduate 33,271 Points[::-2] works fine if the list length is odd. if the length is even, then the last index is odd, and you will get every odd index. so you either need to test for length and cut off the last element if it has an odd index (to use [::-2]), or slice out the evens from the beginning of the list (from index 0), then reverse.
Nemanja Savkic
17,418 PointsI tried the following code in repl and workspaces
def reverse_evens(word):
reverse = word[::-1]
return reverse[::2]
and I got the expected result [5, 3, 1] but it wasn't accepted. Any idea why?
I finished the task by slicing the evens out and then reversing, like James suggested
Albert Tomasura
11,041 PointsAlbert Tomasura
11,041 PointsThanks for your help James. This is what my resulting code.
def first_4(ok):
return ok[0:4]
def first_and_last_4(ok):
return ok[0:4] + ok[-4:]
def odds(ok):
return ok[1::2]
def reverse_evens(ok):