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

I don't know how to do reverse_evens function.

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

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

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

def reverse_evens(iterable): return iterable[::-2]

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

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

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

def reverse_evens(iterable):
    return iterable[::-2]

2 Answers

Steven Parker
Steven Parker
216,175 Points

Good start! What you have will already work half of the time (depending on the length of the list). To make it work for all cases, there's two basic strategies:

  • compute the slice "start" value based on the length (actually even/odd-ness) of the list
  • take the even indexed items and then reverse them with a separate operation

Either method will work when properly implemented. Hint: the second method may be a bit easier to do.

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi, Yusuf Gillani! Looks like you're doing terrific. The last part is a little tricky and your code would work in approximately half of the cases. Namely, it would work when there are an odd number off elements. The example it gives is [1, 2, 3, 4, 5] and expects back [5, 3, 1] which your code does. However, if we change that to [1, 2, 3, 4, 5, 6], it gives back [6, 4, 2] but those are at the odd indexes.

New plan of attack: first pick every other item and then reverse it.

Hope this helps! :sparkles:

edited for minor correction:

Steven Parker
Steven Parker
216,175 Points

In your second example you get the even numbers, but the are at the odd indexes. :wink:

Samuel Blowe
Samuel Blowe
3,011 Points

This helped me a lot. Thank you!