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

JeanMartin Ghecea
JeanMartin Ghecea
5,770 Points

Why doesn't my function work as I wrote it?

I am not sure why my 'reverse_evens" function is not passing. I tested it and it seems to work just find in IDLE and with Workspaces. Thanks.

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

def first_and_last_4(alist):
    return first_4(alist) + alist[-4:]

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

def reverse_evens(alist):
    mylist = []
    for i in range(len(aval),0,-1):
        if i % 2 == 0:
            mylist.append(aval[i])
    return mylist

2 Answers

Aaron Nolan
Aaron Nolan
5,714 Points

You're very close to the correct answer just remember that when you get the length of a list, for example:

alist = [1, 2, 3, 4, 5]

len() will return 5 but the last index is actually 4.

So it actually needs to be written like so:

def reverse_evens(alist):
  mylist = []
  for i in range(len(alist),-1,-1): # You should start at -1, not 0 as that index would be out of bounds
    if (i - 1) % 2 == 0: # -1 so you're checking the correct index
      mylist.append(alist[i - 1]) # -1 so you are appending the correct index
  return mylist

This can also be solved by using slicing also, by checking the size of the list first:

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

Hope this helps and happy coding :)

JeanMartin Ghecea
JeanMartin Ghecea
5,770 Points

Thank you Aaron. Yes, that did it! :)