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 trialVic A
5,452 PointsI don't know what the issue is. I ran it in PyCharm, and it works just fine.
what's wrong here?
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
james south
Front End Web Development Techdegree Graduate 33,271 Pointsyou can chain slices together, like return myList[:-1][::-2]. or from the front you could do [::2] then reverse [::-1].
james south
Front End Web Development Techdegree Graduate 33,271 Pointsa 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
5,452 Pointsok, 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]
Mike Wagner
23,559 PointsI 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.
Vic A
5,452 PointsVic A
5,452 Pointsok didn't know that was possible