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

Daniel Smith
Daniel Smith
10,172 Points

I'm not sure why my reverse evens function isn't working.

The code works in pycharm, perhaps it wasn't expecting the modulus check?

slices.py
def first_4(word):
    return word[0:4]
def first_and_last_4(word):
    return word[:4]+ word[-4:]
def odds(word):
    return word[1::2]
def reverse_evens(word):
    if len(word)%2==0:
        return word[-1::-2]
    else:
        return word[-2::-2]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

You are close. The if condition is inverted. Should be:

len(word) % 2 != 0

That would pass but there is an easier way. What if you use to steps: get the even indexed item, then reverse them?

Post back if you need more help. Good luck!!!

EDIT1:

I've just realised I haven't specified the starting index (in this case the final index) is even OR odd.

This is how I re-wrote it:

def reverse_evens (input):
    if len(input) % 2 == 0:
        return input[::-2]
    else:
        return input[-2::-2]

--

Hi Chris,

I got the first three functions accepted, but it didn't allow my reverse_evens function. I checked it on my IDLE Python 3.6 Shell and it worked; I got [5,3,1] as the output.
Any suggestions?

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

def first_and_last_4 (input):
    return input[:4] + input[-4:]

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

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

TIA,

Ed

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Ed H-P, I looks like your condition is reversed

def reverse_evens(inp):
    if len(inp) % 2 == 0:
        return inp[::-2]
    else:
        return inp[-2::-2]

def reverse_evens_fix(inp):
    if not len(inp) % 2 == 0:
        return inp[::-2]
    else:
        return inp[-2::-2]

print(reverse_evens([0,1,2,3,4,5,6]))
# [5, 3, 1]
print(reverse_evens([0,1,2,3,4,5,6,7]))
# [7, 5, 3, 1]

print(reverse_evens_fix([0,1,2,3,4,5,6]))
# [6, 4, 2, 0]
print(reverse_evens_fix([0,1,2,3,4,5,6,7]))
# [6, 4, 2, 0]

Also, it is recommended to avoid using the name of built-in functions and types, such as input, as variable labels.

Chris you are absolutely correct - I'd mistakenly returned the even numbers instead of even indices. Thanks for the suggestions!