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

Alvaro Sanmartin Cid
seal-mask
.a{fill-rule:evenodd;}techdegree
Alvaro Sanmartin Cid
Python Web Development Techdegree Student 1,065 Points

Problem with slices

I need to return the first and last 4 items of the list, but I don't understand why it keeps saying that it returns the wrong values.

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

def first_and_last_4 (list):
    return first_4(list).append(list[-4:])

2 Answers

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

I see two issues.

  1. You are using append() which will append 1 object into the list - so you last 4 would be inserted a 1 entry list not the 4 individual values. You'll need to use extend() which merges lists.

  2. You'll need to break out the slice steps (I don't understand why well enough to explain) because you just can return slice and extend values. So, create a variable for the first 4, then extend that list with the last 4 and then return you new variable. Your slicing value correct.

You should always run you code in the console/IDLE to verify and debug - only way to see what is happening.

Something like:

def slice_example(list):
    new_list = list[:4] #you can use your function here if you want
    last_4 = list[:-4]
    new_list.extend(last_4)
    return new_list