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 trialvalerakushnir
2,265 PointsSlice Functions not passing challenge 4 of 4
Am I the only one experiencing issues on the last task? I ran this code in the terminal and Sublime text, and it works like a charm.
def first_4(iterable):
return iterable[:4]
def first_and_last_4(iterable):
a = iterable[:4]
b = iterable[-4:]
return a + b
def odds(iterable):
return iterable[1::2]
def reverse_evens(iterable):
return iterable[-1::-2]
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsThe issue is when there are an even number of items in the iterable
:
>>> [1, 2, 3, 4, 5][-1::-2]
[5, 3, 1]
>>> [1, 2, 3, 4, 5, 6][-1::-2]
[6, 4, 2]
The solution is to break it into two steps:
- get even-indexed items
- reverse the list
These two slices can be chained together in a single statement.
Post back if you have any questions. Good Luck!!
valerakushnir
2,265 PointsThat actually worked! thank you!
Eric Laff
5,940 PointsWeird I tried that. I guess I will try again. Thanks!
Hunter Wierstra
7,454 PointsHello Chris Freeman, I am having issues with challenge four of slice functions in tree house python. You said to get even indexed items and then reverse the list. What would that look like?
Chris Freeman
Treehouse Moderator 68,441 Points# Even indexes (two examples)
>>> l0 = [0, 1, 2, 3, 4, 5]
>>> l1 = [1, 2, 3, 4, 5]
>>> even0 = l0[::2]
>>> even0
[0, 2, 4]
>>> even1 = l1[::2]
>>> even1
[1, 3, 5]
# reversing the even indexes
>>> rev_even0 = even0[::-1]
>>> rev_even0
[4, 2, 0]
>>> rev_even1 = even1[::-1]
>>> rev_even1
[5, 3, 1]
# slices can be chained together
>>> long = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> evens = long[::-2]
>>> evens
[11, 9, 7, 5, 3, 1]
>>> evens = long[::2]
>>> evens
[0, 2, 4, 6, 8, 10]
>>> third_and_forth_even = evens[2:4]
>>> third_and_forth_even
[4, 6]
# combine the two slices:
>>> third_and_forth_even2 = long[::2][2:4]
>>> third_and_forth_even2
[4, 6]
Can you see how to solve the challenge in a single statement using slice chaining?
Post back if you have more questions. Good luck!
Albert Tomasura
11,041 PointsAlbert Tomasura
11,041 PointsI tested items[::-2] in Workspaces with the list: items = [1, 2, 3, 4, 5] and it returned [5, 3, 1] just like in the example.
...And it failed