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

How do your return the first 4 and last 4 items in a slice?

I can find the values using a[:4] and a[-4:]. How do I either combine those into one slice or return both?

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

def first_and_last_4(items):
    itemss = items[:4]
    itemss = itemss.append(items[-4:])
    return itemss

2 Answers

Taylor Schimek
Taylor Schimek
19,318 Points

hey lowell.. Your only issue is the .append() method. .append() will add its argument as to the next available index of a list. If you pass it a list, that entire list is put into the next index of the list you're appending. Instead, try the .extend() method.

Hope that makes sense and helps.

David Papandrew
David Papandrew
8,386 Points

With your solution, you would just need to tweak the code. Since you are using the append method, you just type the object followed by the function and the argument.

This will pass:

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

def first_and_last_4(items):
    itemss = items[:4]
    itemss.append(items[-4:])
    return itemss

You could be more concise and do this (where you reuse the first function):

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

def first_and_last_4(items):
    return first_4(items) + items[-4:]

Hi David, Thank you for your input. I have to let you know the system doesn't accept the second suggestion of just using the + to combine the Slices.

I wonder why it requires you to pass the Slices into another Slice before you output it. This seems really inefficient.

Error message from: return first_4(items) + items[-4:]

Result: Traceback (most recent call last): File "<stdin>", line 1 TypeError: can only concatenate list (not "int") to list.