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 trialAbe Daniels
Courses Plus Student 2,781 PointsI am so close.. need help slicing.
I am getting [1,2,3,4,5,49,48,47,46,45] should be getting [1,2,3,4,5,45,46,47,48,49]
I want to be able to solve this with the ability to insert any iterable into var, to make it universal. (Works for 1-100, and 1,-50)
Thanks! :)
question = "Make a function name first_and_last_4 that accepts an iterable and returns the first 4 and last 4 items in the iterable."
var = []
def first_4(var):
return var[:4]
def odds(var):
return var[1::2]
def first_and_last_4(var):
solution = var[:4] + var[:-5:-1]
return solution
2 Answers
Tatiana Jamison
6,188 PointsSince you've passed -1 as the step size, it's traversing the list backwards. You want to traverse the list forward (i.e., with the default step size of "1"), just modify the starting position.
Christian Lapinig
6,396 PointsYou can do something like var[8:] (I know it's supposed to be 4, but you get the picture), it's like you are going backwards in the list much like how var[:8] goes forward in the list and slicing it at how many items you want. You can also simplify the function by doing:
def first_and_last_4(var): return ......
Tatiana Jamison
6,188 PointsTatiana Jamison
6,188 PointsIn case this is overly cryptic, remember that when you do something like
var[:-5:-1]
... the syntax is
iterable[start:end:stepsize]
So it says, "count backward by 1 from the end of var until you reach the element whose index is 5 less than the length of the list."