Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Emil Hejlesen
Emil Hejlesen
3,014 Points

how do you do the second task

create a funtion that takes the first four and four last please help

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

def first_and_last_4(liste2):
    return liste2[:4:-5:-1]

1 Answer

You will need to add two slices together for the first_and_last_4 piece. You already solved the first four problem so you can use that code and then add '+' another slice of just the last four. You can use negative indexes to indicate from the end.

Emil Hejlesen
Emil Hejlesen
3,014 Points

what do you mean like this?

return liste2[:4] +[:-5:-1]

You are on the right track, try forgetting about the first 4 for now since you already have that down. to just create a slice of the last four, you need the name of the list, and start/end locations. so it should look like liste2[-#:]. When you add that extra -1 at the end, you are basically saying you want to keep every other index.

Emil Hejlesen
Emil Hejlesen
3,014 Points

ahhh i get it now thank you :)

Emil Hejlesen
Emil Hejlesen
3,014 Points

i've tried again and i still say it's wrong but i get the right result when i run it on my python shell on my pc

i used this code this time:

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

please explain

you're almost there, you don't need the extra :1 at the end of the second slice.

Emil Hejlesen
Emil Hejlesen
3,014 Points

i cant do that that is a syntax error

Emil Hejlesen
Emil Hejlesen
3,014 Points

found the error was missing an ":" at the end of the function thanks for the help

This is the code, I am not getting a syntax error:

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