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 (Retired) Slices Slice Functions

Bummer, should this not be 46,47,48,49?

As I have struggled with the answer to the slice challenge, I decided to make sure I got the correct last 4. And this is what it gave me:

Bummer! first_4() didn't return the right output. It returned [7, 8, 9, 10] instead of [1, 2, 3, 4].

I did not think we had to make the range first? Did I ASSume wrong? As I thought the range was 0->49.

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

1 Answer

Juan Martin
Juan Martin
14,335 Points

Hello my friend, remember that when you're slicing, the thing goes as this:

[start:stop:step]

With [-4:], it's will start from the position/index "-4", and that's 4 steps from the end, to the end of the list.

For example:

If the end is number 10, then number 10 = position/index -1, number 9 = position/index -2, number 8 = position/index -3, number 7 = position/index -4. So it'll start from the number seven.

The easiest way to solve this is doing it like this:

def first_4(iterable):
  return iterable[:4]

Also, while slicing, when you delimit the "stop" that'll be until that position/index, but not including it, so [:4] will be until position/index 4, but it'll not include it, and will go like this:

[position/index = 0, position/index = 1, position/index = 2, position/index = 3] (doesn't include the position/index = 4)

The resulting list (if it starts with number 1) will be this:

[1, 2, 3, 4]

Note: The challenge says that you're looking for the "first 4", not the "last 4"

Hope this helps :)