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

nakalkucing
nakalkucing
12,964 Points

In the challenge 'Slice Functions' task #2 I keep on getting an error I don't seem to be able to get around.

The error I keep on getting is 'Bummer! Didn't get the right values from first_and_last_4.' which is odd because this same code works fine in workspaces and gives back the answer they're looking for. I've looked this over and over. If anyone can tell me what my problem is I would be grateful. Here are the instructions from the challenge:

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.

slices.py
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

def first_4(iterable):
    slice1 = iterable[0:4]
    return(slice1)
first_4(iterable)

def first_and_last_4(iterable):
    slice1 = iterable[0:4]
    slice2 = iterable[11:16]
    slices = slice1 + slice2
    return(slices)
first_and_last_4(iterable)

2 Answers

Stuart Wright
Stuart Wright
41,118 Points

Remember that the value you pass into your function will not always be the same length. If you pass in something with 20 elements, 11:16 is not going to be the last 4. You need to write the function in a way that is able to retrieve the last 4 elements, regardless of length.

def first_and_last_4(it): return it[:4] + it[-4:]

nakalkucing
nakalkucing
12,964 Points

Hey, thanks for answering rasel. I have already figured out how to fix my code, but thank you for your time. :) All the best, Nakal.