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

Where am i wrong in my code?

I'm trying to get the reverse_evens function to print the list's even indexes out in reverse, but it keeps saying i'm wrong...

slices.py
def first_4(whatever):
    newstuff = whatever[:4]
    return newstuff

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

def odds(uhuh):
    odds = uhuh[1::2]
    return odds

def reverse_evens(uhuh):
    evens = uhuh[-2::-2]
    return evens

2 Answers

Louise St. Germain
Louise St. Germain
19,424 Points

Hi Carlos!

The issue with reverse evens is that your code doesn't know whether the incoming list has an even or an odd number of items, and treats both the same way. Since it starts counting from the 2nd-last item without knowing whether that is an odd or an even list item, sometimes your code is returning the evens, but sometimes it is returning the odds.

There are a couple of ways to fix this. You could get the evens by counting forward the normal way (step size +2), then returning that list of (forward) evens in reverse, using a -1 step size.

Alternatively, you could use an if statement that checks whether len(uhuh) is even or odd (use the modulo function), and use different slices to get the evens starting from the end, depending on whether the list has an even or odd number of items. The only difference will be where the start point is. Both would still have the -2 step size as before.

I think the first way is cleaner, but both should work, and there may even be more ways!

I hope this helps, and good luck with the challenge!

wow that was a well put way to say that...... you're awesome! And it worked! Thanks for the help!

Louise St. Germain
Louise St. Germain
19,424 Points

I'm glad it was helpful, and happy to hear you got it working! :-)