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

Tested answer, but can't get final challenge to pass. Am I doing something wrong?

I am trying to keep the return as concise as possible. I've tested the code in the console in workspaces and return the even indexes to the best of my knowledge. I thought it accounts for the length of the array like stated in another question, but it just tells me it didn't return the correct numbers.

I followed these steps in the code:

  • check if number is even or odd by checking for remainder of length
  • returned backwards count if it's even starting at the even ending
  • else I reversed it and then counted forward by even indexes
  • I tried to adjust the odd count incase i was hitting odds instead of even with no change to trial response.
  • I searched forums
  • I grimaced.

Any help would be appreciated.

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

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

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

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

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

It's not doing what you think:

>>> print(reverse_evens([1,2,3,4,5]))
[5, 3, 1]

>>> print(reverse_evens([1,2,3,4,5,6]))
[6, 4, 2]

Hint: think get even indexs first, then reverse it.

Nice use of slice of a slice!

Oh dang! I was thinking the problem was with the else condition and not with the even slice. Thanks Chris Freeman for helping out with the results. I was not iterating over the even indexes of the even slice, but the indexes of the even numbers. lol. Once I fixed it it was fine.