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 trial

Python Python Collections (2016, retired 2019) Slices Slice Functions

Joseph Jackiewicz
Joseph Jackiewicz
2,102 Points

Struggling to concatenate two slices

I was able to answer the first question and I believe I can correctly return the two slices but I keep getting the message Bummer! Try again! and I'm not sure why

slices.py
def first_4(item):
    return item[0:4]

def first_and_last_4(item):
    return (item[0:4] + item[:-4:-1]

2 Answers

You are very close here. If the list was [1, 2, 3, 4, 5, 6, 7, 8] you would get back [1, 2, 3, 4, 8, 7, 6] because -1 in item[:-4:-1] is going from the end of the list back to, but not including the fourth from last item.

Try this:

def first_and_last_4(item):
    return first_4(item) + item[-4:]  # corrected my original answer.

EDIT: My original post I wrote on my iPhone and missed typed my answer. I had put:

def first_and_last_4(item):
    return first_4(item) + item[:-4]  # this will return the first 4 (by using the previous method) but concatenates a slice from index 0 - 4th from last.

This is incorrect as Mark Mneimneh points out below.

This won't work
try it with a [1,2,3,4,5,6,7,8,9,10,11,12]

you will get 
[1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7, 8]
which is incorrect

item[:-4] means, start from beginning and end @ end -4.  which is not same as first 4 and last four.

see if this will work

def first_and_last_4(item):
    return (item[0:4] + item[len(item)-4::])

and keep in mind ... there are other ways to achieve same thing.

You are correct. My code will not work. I meant to type item[-4:] but I was typing on my phone. I have corrected my answer.

Your answer will work, but it does seem to be redundant. When using a slice, it is not necessary to get the length of the object being sliced.

item[len(item)-4:]  # you are essentially writing item[(12-4):] where 12 is from your example the amount of items.
item[-4:]  # this is just saying start from the fourth from last item and continue to the end. There is no need to get the length.

but as you have stated, there are many ways to do the same thing.