Python Python Collections Slices Slice Functions

Gregory James
Gregory James
Python Web Development Techdegree Student 5,525 Points

First four and last four

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

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

4 Answers

wilmington
wilmington
8,257 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!

wilmington
wilmington
8,257 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