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

no idea whats wrong here

Not really sure how I can combine both lists into a single variable

slices.py
def first_4(x):
    new_x = x.copy()
    return new_x[:4]

def first_and_last_4(x):
    new_x = x[:4]
    other_x = x.copy()
    other_x = [-4:]
    new_x.extend(other_x)
    return new_x

1 Answer

Eric M
Eric M
11,546 Points

Hi Theodore,

Your logic makes sense, but extend doesn't seem to work here, perhaps we're not always getting lists as our iterable so we can't use list methods?

There are two things we can do though, one's really easy. Just add the slices together using the addition operator +.

rtr_x = new_x + other_x should be a fine return value.

You also don't need to do use x.copy() as slice already creates a new object, it doesn't mutate what you're slicing. This is true when you're assigning a slice to a variable at least (when the slice is on the right hand side of the assignment operator =).

When you're assigning values to a slice it works a little differently. Slice can give you an insertion point (or replacement range) in an existing iterable when it's on the left hand side of the assignment operator. We get an insertion point when we give it a range with nothing in it.

For instance, this code to insert the first slice into the start of the second using only slices and assignment is able to pass the challenge:

def first_and_last_4(itr):
    a = itr[:4]
    b = itr[-4:]
    b[:0] = a
    return b