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!

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

First four and last four

I am trying to keep it simple. Please give me a hint.

def first_4(info):
    return info([-4:]+[:4])

4 Answers

9,845 Points

Hey Gregory,

Let's look at you function where you slice the elements of your iterable variable (whatever it is). you wrote info([4:;] + [;;-4]). In your brackets[], the first position is for the starting index value, the second position is for the ending index value and the last position is a step. Thus, for example, if it is [0:4:1] it means from index 0 to index 4 (not including) with step 1. You can similarly do [:4:1] - here, the missing first position means from the very start, the second position is up to forth index but not including, and the last position is the step, but the default step is 1, so we don't need it. With this said we actually need [:4].

Coming to the slicing of the last 4 elements of your iterable, you need to start is from the forth element from the back, which is position [-4] till the end, so it is [-4:]. Just to remind you we can count index positions backward, so the last one is [-1], the one before the last one is [-2] and so on. Hope it will help!

By the way, do not forget to double check the name of your function to match the one in the task and make sure you are adding the next function in the task to the previous one i.e. if you are working on first_and_last_4, make sure you still have the function for the previous task first_4 at the top. All the following tasks you are adding to the previous tasks, otherwise you'll get an error in the workspaces, referring to the previous tasks' errors.

Good luck!

like this?

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

9,845 Points

Hey there,

It seems your are very close to it. First of all, make sure the name of the function matches the name in the task. Note the wording of the task, which states the first 4 and the last 4. In your case it is the opposite. I am not writing a ready code here, since you almost did it. Just give it another look. Good luck