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 trialorenbatsoren
2,727 Pointsiterable with even function
Make a function named reverse_evens that accepts a single iterable as an argument. Return every item in the iterable with an even index...in reverse. For example, with [1, 2, 3, 4, 5] as the input, the function would return [5, 3, 1].
what am i doing worng?
def first_4(a):
return a[:4]
def first_and_last_4(b):
return b[:4]+b[-4:]
def odds(c):
return c[1::2]
def reverse_evens(x)
return x[::-2]
3 Answers
james south
Front End Web Development Techdegree Graduate 33,271 Pointswhen you slice [::-2] you are starting at the end and going to the start by twos, but depending on whether the length of the list is an even number or not (and therefore whether the last index is an odd number or not), you may or may not slice the even indices. you can slice by twos from the start of the list, THEN reverse, or, to use [::-2], you will need to test for length and cut off the last element if it has an odd index (ie if the list length is even). then you would be starting your slice on an even index and be ok.
orenbatsoren
2,727 PointsThank you!!
orenbatsoren
2,727 PointsThank you Chris.
Chris Freeman
Treehouse Moderator 68,441 PointsWhy was this answer voted down?
orenbatsoren
2,727 PointsVery sorry, i did it by mistake.
Chris Freeman
Treehouse Moderator 68,441 PointsGood to correct so it doesn't cost you a point!
Chris Freeman
Treehouse Moderator 68,441 PointsThough I think the Best answer should be James South's answer.
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsAlso note that you can use a slice of a slice where the first slice gets the even indexed items, and the second slice reverse the first. Use the format
somelist[start1:stop1:step1][start2:stop2:step2]
filling in the appropriate values.