Python Python Collections Slices Slice Functions

Kars Jansens
Kars Jansens
2,007 Points

This is working in my IDE [Python] slices

The question is: You're on fire! Last one and it is, of course, the hardest.

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

You can do it!

In my IDE this works fine. I really don't understand why this doesn't work.

slices.py
def first_4(variable):
    return variable[:4]


def first_and_last_4(variable):
    variable[:4] += variable[4:]
    return variable[:4] + variable[-4:]

def odds(variable):
    return variable[1::2]

def reverse_evens(variable):
    return variable[::-2]

3 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 142,446 Points

Hi Kars Jansens

Yes, if you send in an odd number of items in the list (eg. 1, 2, 3, 4, 5)... that code will work. But, did you test that code with an even-numbered list (eg. 1, 2, 3, 4, 5, 6)? With that, the code won't work.

I'll give you a hint: You could use an if statement to test if it's an even or an odd numbered list and then use the appropriate slice function on it.

The rest looks great. Nice work! :) :dizzy:

Kars Jansens
Kars Jansens
2,007 Points

I do not understand how I can do this with an if statement, so I tried it with a try statement.

def first_4(variable): return variable[:4]

def first_and_last_4(variable): variable[4:] += variable[:4] return variable[:4] + variable[-4:]

def odds(variable): return variable[1::2]

def reverse_evens(variable): try: variable[::-2] except TypeError: variable.remove(variable[-1]) return variable[::-2]

It works fine with every amount of numbers in my list in pycharm. But it still doesn't work.

Jason Anders
Jason Anders
Treehouse Moderator 142,446 Points

In my opinion, an if statement is best. A try block will not work for this test, and you can't remove something from the list just to make it fit the criteria. If this were a real-life scenario, you wouldn't go removing items from a list just to make your code work, right?

With an if statement you test the incoming list to see if it is an even length or an odd length. This would be done with the modulus operator. Once you figure the length, you simply start the slice either at the last item (odd list) or at the second-to-last item (even list) and then progress the slice like you have in your code. Where to start the slice goes on the right of the :: and the incremental movement goes on the left.

The code will look something like this:

def reverse_evens(variable):
    if len(variable) % 2 == 0:  # testing the list
        # even list code here
    else:
        # odd list code here

You should be able to get it from here. :)