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

james mchugh
james mchugh
6,234 Points

I'm not sure if they want odd or even number

It says return even numbers starting at the end of the list, but the example shows odd numbers. Not sure what they want so I tried returning both, but it just tells me try again.

slices.py
def first_4(data):
    return data[:4]
def first_and_last_4(data):
    return data[:4] + data[-4:]
def odds(data):
    return data[1::2]
 def reverse_evens(data):
        return data[::2]

1 Answer

Eric M
Eric M
11,545 Points

Hi James,

Task 4: 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].

While the numbers are odd, they have even indexes in the array.

For an array of: arr = [1, 2, 3, 4, 5]

Its indexes are (as with every array): [0, 1, 2, 3, 4]

So the even index are: [0, 2, 4]

Which correspond to the values in arr of: [1, 3, 5]

So the reversed array of even indexes from the original array is: [5, 3, 1]

So we need a function similar to:

def reverse_evens(data):
    return (data[::2])[::-1]

The data[::2] ensures we step over all of the odd numbers, then [::-1] reverses the new list that contains only evens. While data[::-2] would work for the example, it wouldn't work for a list that had one other item, that would instead return all of the odd indexes, hence the 2 step approach.

Cheers,

Eric

james mchugh
james mchugh
6,234 Points

Hi Eric, Thanks again for your help. You really spelled it out. I'm gonna save those notes you wrote here.