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 trial

Python Python Collections (2016, retired 2019) Slices Slice Functions

orenbatsoren
orenbatsoren
2,727 Points

iterable 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?

slices.py
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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

when 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.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Also 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.

orenbatsoren
orenbatsoren
2,727 Points

Very sorry, i did it by mistake.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Though I think the Best answer should be James South's answer.