Python Python Collections Slices Slice Functions

James Dunn
James Dunn
2,739 Points

Why isn't this working

Here is my code.

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

def first_and_last_4(new_list): temp_list = new_list[:4] temp_list2 = new_list[-1:-5:-1] temp_list.extend(temp_list2) return temp_list

The challenge wants me to return the first and last 4 digits of a number and return them as a single value.

I plugged it into my python IDE and the code for the first_and_last_4 function work correctly.

What am I missing?

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

def first_and_last_4(new_list):
    temp_list = new_list[:4]
    temp_list2 = new_list[-1:-5:-1]
    temp_list.extend(temp_list2)
    return temp_list

3 Answers

Steven Parker
Steven Parker
155,816 Points

One issue with testing challenges in external REPL's is that it's easy to misinterpret the goal, which seems to have happened here.

The instructions for the "first_and_last_4" function do not say that the last four should be returned in reverse order. Extract the last four in the original order and you should pass the challenge.

James Dunn
James Dunn
2,739 Points

I thought of that. And just tried adding the following line to reverse the order.

temp_list2 = temp_list2[::-1]

However, it keeps telling me that the wrong numbers are being returned by first_and_last_4. Or are you saying I need to get the last four in the right order from the on set?

Thanks for your help.

James Dunn
James Dunn
2,739 Points

Neeeeverrrr mind. Turns out I was using append() when I needed extend().

Again, thank you.

Steven Parker
Steven Parker
155,816 Points

James Dunn — The original solution above does use extend, but it also had a negative step in the slice.

Anyway, glad to help. You can mark the question solved by choosing a "best answer".
And happy coding!