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

Josh White
Josh White
3,630 Points

Code working but not completing the challenge

I put this code in thinking it's the neatest way of having both the first 4 and last 4 into a single value. I have tested this code with strings and integers and they work on my editor but it's saying that I am wrong in this challenge.

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

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

1 Answer

Gabbie Metheny
Gabbie Metheny
33,778 Points

I can't quite figure out why the challenge isn't accepting your solution (could be something buggy), but probably a simpler way to get the last 4 is [-4:]. Let me know if that doesn't work!

Gabbie Metheny
Gabbie Metheny
33,778 Points

Okay, looks like the challenge wants to maintain the order of the items, but your current code is returning the last 4 in reverse.

list = 'elephants'

list[:4] + list[-1:-5:-1]    # returns 'elepstna'
list[:4] + list[-4]    # returns 'elepants'
list[:4] + list[-1:-5:-1][::-1]    #returns 'elepants'

That last example works because it takes the 'stna' slice and makes a new slice of it, from beginning to end, reversing the step. Clunky, but technically correct.