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

please help me figure out what's wrong with my code

Didn't get the right values from first_and_last_4.

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

def first_and_last_4(alpha):
    alpha = list(str(alpha))
    first = alpha[:4]
    alpha = alpha[::-1]
    last  = alpha[:4]
    first.extend(last)
    string_value = "".join(first)
    return string_value

1 Answer

Steven Parker
Steven Parker
229,783 Points

You're working too hard! Getting the "last 4" can be done almost exactly the same way as you get the "first 4", except that the slice will use a "start" value instead of a "stop".

Then, you can just concatenate the "first 4" and "last 4" together. No need to do any string or list conversion.

So true about the conversion part. But I don't know where the index of the "last 4" starts, that's why I tried to get the reverse of the list.

Steven Parker
Steven Parker
229,783 Points

You could compute the index using the length, for example: "len(items)-4". But in slices, negative values mean "from the end". So the starting point for the last 4 items could also be written simply as -4.

I've tried using the negative [-4:] index as the starting position before. Doesn't work. I'll move on from this problem for now, and come back to it later on. Thanks!

Steven Parker
Steven Parker
229,783 Points

That's the correct slice syntax, perhaps you had used it in combination with code that had other issues. Try it again, and if you still have trouble, post the complete code as it is now.