Python Python Collections Slices Slice Functions

Jan Durcak
Jan Durcak
2,958 Points

In this first o

hey guys, why is this not working for me

def first_4(thing):

for i in thing[0:4]:
    return i
slices.py
def first_4(hey):

    for i in hey[:4]:
        print(i)
Sebastiaan van Vugt
Sebastiaan van Vugt
3,466 Points

Hi - I tried your function and it works for me. Just insert an iterable and it will return the first four items in your "thing" (which you have called "hey"). If for example, I call the function underneath:

def first_4(hey):

    for i in hey[:4]:
        print(i)


first_4("Sebastiaan")

I will get, one by one, the characters returned from the 0'th, 1st, 2nd and 3rd (up to but not including the 4th) index which are the first four characters of my name. I hope that helps :)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 55,159 Points

You are very close. The challenge is asking for the 4 values to be return as one object. With the return Inside the for loop, it will return only the first character.

Remove the for loop and directly return the whole slice you’ve made.

Post back if you need more help. Good luck!!!

Luke Maschoff
Luke Maschoff
820 Points

I still don't get it? Here is my code:

def first_4(item):

    for i in item[0:4]:
        return i
Chris Freeman
Chris Freeman
Treehouse Moderator 55,159 Points

Your code with return the very first time it hits the return statement. This will happen the first time through the for loop. The for loop will iterate through item[0], item['1'], item['2'], item['3']. However, while looping with the first item['0'], the return statement is hit, and the integer 1 will be returned.

You have the desired return value of item[0:4]. If you remove the for loop, you can simply use return item[0:4].

Does this help?

Jan Durcak
Jan Durcak
2,958 Points

Thx for your time guys