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

Harper Frankstone
Harper Frankstone
5,156 Points

Getting the last 4 items in a slice

I need to get the first 4 items, and the last 4 items in an iterable, by slicing. The function needs to return the first and last 4 items in a single variable. I think I am close but I'm not sure why it isn't working. Any help is appreciated! Thanks!

def first_4(obj):
    items = obj[0:4]
    return items

def first_and_last_4(obj):
    first = obj[0:4]
    last = obj[-4::-1]

    first_last = first.extend(last)
    return first_last
Van Sanders
Van Sanders
16,087 Points

Keep in mind that the brackets separate the 'start', 'stop', and 'step' like so: [start:stop;step]

So, in your last slice, you should try just defining the start so that it is 4 items from the end of the list.

Then, don't worry about the -1 step. That will make the returned value be reversed, since it will be counting from the back of the list! Just make sure your start point is -4.

Also, no need to use the extend notation. You can just return first + last.

I hope that helps!

Harper Frankstone
Harper Frankstone
5,156 Points

Hey Van, so I took the step out of that last slice, but my code is still being rejected. Starting the slice at -4 should return the last four items, correct?

1 Answer

Hi there,

I used obj[:4] for the first four and the simply added with + the last four like obj[-4:]

That looked like:

def first_and_last_4(obj):
    return obj[:4] + obj[-4:]

I hope that helps,