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

Travis John Villanueva
Travis John Villanueva
5,052 Points

Please help. Just to get a goodnight sleep :)

I dont see why my code is wrong. I even tested it in my workspace

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

def first_and_last_4(x):
    a=x[:4]
    b=x[len(x)-4:]
    c=a+b
    d="".join(map(str,c))
    return d

Steven Parker - Will do, thanks for the heads up.

2 Answers

So from your code, I'm assuming you're on Task 2/4.

Task 2 is: OK, this second one should be pretty similar to the first. Make a new function named first_and_last_4. It'll accept a single iterable but, this time, it'll return the first four and last four items as a single value.

So the way we can achieve this is by using a cool feature of slices. So what we can do is ask for x amount of items from the end of the list.

So for example:

# Let's say we have this list here in the variable x
x = [1, 2, 3, 4, 5, 6, 7, 8]
# We can use a negative number to get the numbers from the end of the list.
x[-2:]
#Would return
[7, 8]

So going back to what we want to do for this question is simply get the first 4 numbers and the last four. Then return a single list with those 8 numbers.

def first_and_last_4(x):
    #To get the first four we can replicate the code created in the first task or call that function.
    first_four = x[:4]
    # Then to get the last four we simply just use a negative four to get them
    last_four = [-4:]
    # Lastly we return it.
    return first_four + last_four

An even cleaner solution would be:

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

This code will pass the challenge:

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

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

My issue with this challenge was returning the last 4 in reverse order. I was able to pass doing:

def first_and_last_4(list):
      new_result = list[:4] + list[-4:]
      return new_result