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

Vic A
Vic A
5,452 Points

I don't know what the issue is. I ran it in PyCharm, and it works just fine.

what's wrong here?

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

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

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

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

3 Answers

Vic A
Vic A
5,452 Points

ok didn't know that was possible

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

a slice of [::-2] doesn't return the even indices if the length is even. it returns the last index, and every other index, going backwards, so if the length is even, the last index is odd, and you get the odd indices, not the evens. to fix either slice the evens from the front, THEN reverse, or test for length and cut off the last index if odd, then use [::-2].

Vic A
Vic A
5,452 Points

ok, I fixed it using this, but just for my own knowledge whats the shortest/cleanest way to write this?
if len(x) % 2 != 0: return x[::-2] else: y = x[:-1] return y[::-2]

I would, personally, build the array you want first, then reverse it.

def reverse_evens(a):
  b = a[::2]
  b = b[::-1]
  return b

I'll link you to this question where I answer why in more detail.