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

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 68,441 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 68,441 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.