Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,515 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.