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 trialTiago Ramos
2,380 Pointswhy 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
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
231,269 PointsYou'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.
Tiago Ramos
2,380 PointsTiago Ramos
2,380 Pointshey 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?
Tiago Ramos
2,380 PointsTiago Ramos
2,380 PointsAnd I have no ideia how to calculate the staring position, and how can I use that to return the reverse evens
Steven Parker
231,269 PointsSteven Parker
231,269 PointsIf 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]
").