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

Brent Capuano
Brent Capuano
949 Points

what am i missing?

Shouldnt this give me the last 4 going straight through the first 4?

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

def first_and_last_4(x):
    return x[-4:4]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

What you have returns from the 4th-from-last to the 4th-from-front. This is the empty list:

>>> [1,2,3,4,5,6,7,8,9,10][-4:]
[7, 8, 9, 10]
>>> [1,2,3,4,5,6,7,8,9,10][-4:4]
[]

You need to get the first four and last four separately then combine and return.

Post back if you need more help. Good luck!!!

Brent Capuano
Brent Capuano
949 Points

why doesnt it work if the list moves from left to right it should hit the last 4 and then give the first 4???

Chris Freeman
Chris Freeman
Treehouse Moderator 68,457 Points

[-4:4] returns nothing since the second index is less than the first index

Chris Freeman
Chris Freeman
Treehouse Moderator 68,457 Points

Each slice returns a single contiguous part, or an empty list if start is after stop. The second index is not relative to the first:

>>> [1,2,3,4][-4:4]  # first index same as 0
[1, 2, 3, 4]
>>> [1,2,3,4,5][-4:4]  # first index same as 1
[2, 3, 4]
>>> [1,2,3,4,5,6][-4:4]  # first index same as 2
[3, 4]
>>> [1,2,3,4,5,6,7][-4:4]  # first index same as 3
[4]
>>> [1,2,3,4,5,6,7,8][-4:4]  # first index same as 4
[]