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

I can complete the last challange this way? please enter

hi, i can complete the last challange with this CHECK instead of usuing slices?

def reverse_evens(arg1):
    if arg1 % 2:
        return arg1
reverse_evens([1,2,3,4,5,6,7,8,9])

i tried it on the REPL but it didnt worked and i dont know why. i will appreciate ur help.

slices.py

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,722 Points

I like your approach, I tried it too and found out the test data are cleverly constructed such that you can only use a slice approach (or iteration would work too), but

the slice approach is what the instructor expects you to do. What could go wrong? ;-)

Recall, with slices the first part is the "starting point", the second part is the "ending point," the third part is the "step."

You can solve the challenge with a divide-and-conquer strategy. First make a list of even-index elements, then reverse that list. It works for even or odd length lists.

To produce evens, you would have the first argument be zero, or blank, the second argument would be blank which means go to the end of the list, and the third argument would be 2 (step from even element to even element).

def evens(mylist):
    mylist[0::2] # this starts at position 0 and steps to the END of the list by steps of 2

Reversing is incredibly easy with slices-- use -1 as the first slice argument, that means start at the END of the list, then the middle argument should be blank, because you want to end at the BEGINNING, and the last argument is -1, so we step backwards 1 at a time.

def reverse(mylist):
    return mylist[-1::-1] # start at end of the list, go backward to the beginning by steps of 1

I hope this helps... enjoy your Python journey, you might see some green unicorns and pink ponies along the way!

(green unicorn) https://gunicorn.org/

(django pony) http://www.djangopony.com/

I really apperciate your answer! now i know why this way couldn't work in the challange, and u explained to me again how to solve it. thanks in advance :D