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 trialJoseph Martin Nograles
4,696 PointsCoding Challenge Python: First 4 and Last 4 of a list
def first_and_last_4(x): return x[0:4] + x[-5: -1]
Why does slicing a list using [-5 : -1] return me numbers starting at the second last item on the list? Shouldn't -1 start at the last item on the list?
def first_4(new_list):
return new_list[0:4]
def odds(return_odds):
return return_odds[1: :2]
def first_and_last_4(x):
return x[0:4] + x[-5: -1]
1 Answer
Idan Melamed
16,285 PointsGood question...
slice[x:y] is slicing from x to y-1. So slice[-5:-1] will produce the section from -5 to -2. Just like slice[0:4] will produce the section from 0 to 3.
If you want the last 4, you can do it with slice[-4:]
Joseph Martin Nograles
4,696 PointsJoseph Martin Nograles
4,696 PointsYeah makes sense... I was just thrown off coz the video used [-1] to get the last digit.
Thanks for your help!