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

Pratham Patel
Pratham Patel
4,976 Points

Can I get some help with this code challenge

I don't understand the negative index

slices.py
def first_4(list):
    return list[0:4]
def first_and_last_4(list):
    return list[0:4] list[-4:-1]

3 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

You've figure it out except for one litle thing. Slices don't include the end of the slice. Since you're slicing to -1, you'll never get the last item. What happens when you leave the stop argument off of a slice?

Pratham Patel
Pratham Patel
4,976 Points

I switched around the -4 and -1 but it still did not work

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Yeah, it wouldn't. You can't move from -1 to -4 by adding 1.

So, answer my question. What does a slice do when you leave off the second part? If you did list[3:], what would you get?

Pratham Patel
Pratham Patel
4,976 Points

It would start at 3 and go to the end of the list

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

OK, and this challenge wants you to start at -4 and go to the end of the list...

Pratham Patel
Pratham Patel
4,976 Points

I took out the one and wrote [-4:] but it says try again

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You need to combine the two slices.

Pratham Patel
Pratham Patel
4,976 Points

I'm not sure how to do that I searched it but they say you need to use a function