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

Why is it not working?

It works when I type it in console...

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

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

def odds(list3):
    return list3(1::2)

3 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

you need square brackets on the odds return statement.

Thanks, but now this one does not work and it works in console...

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

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

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

def reverse_evens(list4)
    return list4[-1::-2]
Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

Cool... you got pretty far and you are close. The reverse evens is trickier than it seems. Here's the hint. Reverse the list, then return the even elements.

recall that reversing a list can be accomplished by the slice below. I think you know how to do evens!

Best of luck!!

mylist = [1,2,3,4]
mylist_reverse =mylist [::-1]

It still does not work..

It's weird, why does it work in console and not here?

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

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

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

def reverse_evens(list4)
    rev_list = list4[::-1]
    return rev_list[::2]
Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

You are so close!! But a couple of tiny issues here.

  1. You were missing a colon on reverse_evens
  2. My bad advice ;)

I'll explain my bad advice: I interpreted the question wrong. When Kenneth asks for "reverse evens" that can be interpreted as either approach "A" or approach "B". "A" is the correct interpretation.

A) get the evens then reverse the list

mylist[::2][::-1]

B) get the reverse of the list then take the even elements.

mylist[::-1][::2]

Here's why--

On list [1,2,3,4,5] either A or B passes: reverse_evens_A= [5, 3, 1] reverse_evens_B= [5, 3, 1]

On the list [1,2,3,4,5,6] reverse_evens_A= [6, 4, 2] reverse_evens_B= [5, 3, 1]

I swear this passes the challenge (below) ;-)

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