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

Jan Durcak
Jan Durcak
12,662 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Sebastiaan van Vugt
Python Development Techdegree Graduate 13,554 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 68,441 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 68,441 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
12,662 Points

Thx for your time guys