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 trialAndy Bosco
Courses Plus Student 681 Pointsreturns the first 4 and last 4 items in the iterable
This is challenging and so far I can't find anything on Google for Slicing the "first 4 and last 4 items in the iterable." What am I doing wrong?
def first_4(num):
return num[0:4]
def odds(odd):
return odd[1::2]
def first_and_last_4(filter):
return filter[3:-3:]
1 Answer
Michael Norman
Courses Plus Student 9,399 PointsIn the first part of the challenge you did first_4, so that part is complete. All we really need to worry about now is the last 4. You may remember that when we want the item at the end of a list, say my_list, can user
my_list[-1] # last element
my_list[-2] # next to last element
Using negative indices we can get the forth element from the end using an index of -4 and continue to the end of the list using a colon as before. Since lists are mutable we can concatenate the two and return that answer
def first_and_last_4(filter):
return first_4(filter) + filter[-4:]
Andy Bosco
Courses Plus Student 681 PointsAndy Bosco
Courses Plus Student 681 PointsThank you. I didn't know you can add the List together. Now I know.