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 trialKirome Thompson
5,350 PointsHow to return the first and last four items in a list?
I have this which works exactly as intended on my windows Powershell when I input a range of numbers between 0 and 20: def first_and_last_4(a_list): first = a_list[0:4] last = a_list[-1:-5:-1] return first + last output I get is: [1, 2, 3, 4, 19, 18, 17, 16]
def first_4(a_list):
return a_list[0:4]
def first_and_last_4(a_list):
return a_list[0:4]+ a_list[-4:-1:-1]```
5 Answers
caits
4,578 PointsI think the problem is that you're counting backwards for the last 4, so the numbers are in the wrong order. Try starting from -4 to the end of the list.
Kirome Thompson
5,350 PointsThanks very much I appreciate that it worked I had tried using 15:19 but did not work, but thanks again :)
Kirome Thompson
5,350 Pointsmy bad it didn't work seems to me this compiler may have its own set of problems
caits
4,578 PointsCan you share your new code?
Kirome Thompson
5,350 Pointsas requested
caits
4,578 PointsWhen using slices, remember that it's like this: [start:stop:step] So in your case,
a_list[-4:-1:-1]
is really saying, "start at the 4th item from the end and go up to, but NOT including, the last item, but do it in a step of one from the end." I know it sounds silly, but that's what it is. You want to start at 4th from the end, and go all the way to the end. Remember that in slices, if you leave the numbers before and after the colon blank, like this:
a_list[:]
it will slice from beginning to end. In the example list you give of numbers 1 - 20, you would want to get back [1, 2, 3, 4, 17, 18, 19, 20].
I hope that helps. If not, let me know.
Kirome Thompson
5,350 PointsHi thanks yes that cleared things up a lot for me thank appreciated!