Python Python Collections Slices Slice Functions

Jinman Kim
Jinman Kim
5,586 Points

Does anyone have an answer to this question?

I figured out that I can't go from negative index to positive index or vice versa. Okay, so that's fine, I will combine the two lists (first 4 and last 4). Although that gives me a right answer from the workspace REPL, it gives me an error from the quiz. Can anyone please tell me why?

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

def first_and_last_4(word):
    return word[0:4] + word[-1:-5:-1]

1 Answer

Steven Parker
Steven Parker
163,107 Points

This code is returning the last four items in reverse order, but reversing the order is not part of the challenge instructions. To pass the challenge, your function should return the first and last four items in their original order.

Jinman Kim
Jinman Kim
5,586 Points

If I try to put the last four items in their original orders, I can potentially do word[-4:-1] and insert/append the word[-1] but I thought that was not a clean way to write the code (It seems that I can't slice from [-4,0]) Wondering if there is a better way to do this.

Jinman Kim
Jinman Kim
5,586 Points

I have it figured out now! To get the last four I did, word[-4:]