Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Slices Slice Functions

Benjamin Harris
Benjamin Harris
8,872 Points

With [1, 2, 3, 4, 5] as the input, the function would return [5, 3, 1].

I have tested this is work spaces and returned 5, 3, 1. What am I doing wrong? : (

slices.py
def reverse_evens(your_list):
    new_list = your_list[::-2]
    return (new_list)

def odds(your_list):
    new_list = your_list[1::2]
    return (new_list)

def first_4(your_list):
    new_list = your_list[:4]
    return (new_list)

def first_and_last_4(your_list):
    new_list = your_list[:4] + your_list[-4:]
    return (new_list)

2 Answers

Benjamin Harris
Benjamin Harris
8,872 Points

I fixed my code.

I first made a new_list simply stepping through on even indexes then changed that new list to a reverse of itself inside the same function.

eg: new_list = your_list[::2] new_list2 = new_list[::-1] return (new_list2)

I don't really understand why I needed to do that but it worked. let's get stuck on the next question now. : )

Steven Parker
Steven Parker
216,057 Points

The different logic is necessary because otherwise for some lengths it would return reverse evens, but for others it would return reverse odds. There's two strategies to always return reverse evens:

  • compute the starting position based on the list size
  • extract the even index values first, then reverse them (as you did)

FYI: it's possible to make your solution more compact by eliminating the intermediate variables:

   return your_list[::2][::-1]