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

jmac pd
jmac pd
11,490 Points

hmm, am I reading this one wrong? I ran the function through the shell and it returns [5,3,1]

question says to count down "even" in reverse so that list [1, 2, 3, 4, 5] would return as [5, 3, 1] (though this seems like reverse odds, the question was not completed when I ran the function with a [-2: :-2]slice/step returning [4, 2])

slices.py
def first_4(item):
    item = list(item)
    return item[0:4]

def first_and_last_4(item):
    first = first_4(item)
    item = list(item)
    return first + item[-4:]

def odds(item):
    item = list(item)
    return item[1::2]

def reverse_evens(item):
    item = list(item)
    return item[::-2]

You don't need item = list(item) because slice works on every iterable.

item[::-2] returns [5, 3, 1] for list [1, 2, 3, 4, 5], but what if list is [1, 2, 3, 4, 5, 6]?

jmac pd
jmac pd
11,490 Points

ok I got it. thanks Igor:

I added an if/else clause to determine if the length of the iterable was even and then added a variable to the slice:

'''python3

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

jmac pd, you don't need to know if the length of iterable is even or odd:

def reverse_evens(item):
    return item[::2][::-1]