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

Devin Roark
Devin Roark
4,608 Points

when i use [::-2] on my iterable in workspaces set to the example, i get [5, 3, 1] like it asks

Not sure what I'm missing

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]
Devin Roark
Devin Roark
4,608 Points

from trial and error it looks like the answer is return iterable[-1::-2] but i'm still not sure why that works, at least why it works for a list like [1, 2, 3, 4, 5] when the wrong answer didn't work for a list like [1, 2, 3, 4, 5, 6]

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,986 Points

iterable[::-1] produces the correct result when there are an odd count in the list, but not of there are an even number of items.

Use a two step process:

  • get the even elements: [::2]
  • reverse the list: [::-1]

These can be chained together.

Post back if you need more help. Good luck!

Devin Roark
Devin Roark
4,608 Points

EDIT: Derp i read your chain backwards. return iterable[::2][::-1] worked for me.

Chris Freeman
Chris Freeman
Treehouse Moderator 67,986 Points

To be fair. My original answer had the bullets in the opposite order. I've since corrected the order.

I got an email about answering this, but Chris beat me haha Thanks for answering, Chris! D.