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

Serkan van Delden
Serkan van Delden
13,094 Points

first_and_last_4

I just cannot pass the 2nd challenge, because I need to return the first AND the last four words. I really don't know how to do this and I'm stuck here so can anyone please reply?!

slices.py
def first_4(word):
    return word[:4]
def first_and_last_4(word2):
    return word2[1:4-1]
wayne ross
wayne ross
3,225 Points

I am VERY new to programming but I would say with a very quick glance at this can you just cat both slices in the same return like

def first_and_last_4(word2):
    return (word2[:4]+word[-4:])

1 Answer

Vidhya Sagar
Vidhya Sagar
1,568 Points

Yes, @Wayne Ross is right. You can do it like that. But from analyzing your code, you have missed a colon in the return command of the second function. I think the logic you have tried to use is, you thought list would be first reversed and then you can take the first element to the fourth element. But since you used the command return word2[1:4:-1], what the compiler interprets whenever you specify all the three numbers in the slices it means [starting index: ending index-1: increment/decrement factor] . So it tried to find the elements in the list starting from index 1 to index 3(4-1) and the increment factor you have given is -1. Going from 1 to 3 with an increment factor of -1 is not possible, so it returns an null list. I have tried to simplify it for you with a step by step breakdown, Hope this helps.

def first_4(word):
    return word[:4]
def first_and_last_4(word):
    #list is [1,2,3,4,5,6,7,8]
    reverse_word=word[::-1]
    #Reverses the list [8,7,6,5,4,3,2,1]
    last_four_in_reverse=reverse_word[:4]
    #Gets[8,7,6,5], But answer required is [5,6,7,8] for last four, so reversing this in the next step
    last_four=last_four_in_reverse[::-1]
    answer=word[:4]+last_four
    return answer