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

hello, why does this function work?

def first_4(iter): iter=iter[:4] return iter

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


iter = 'safadsfasdlfkjasdlfkj'

result = first_4(iter)

print (result)

2 Answers

thanks!!!

Cooper Runstein
Cooper Runstein
11,850 Points

I'm going to assume you're asking why it doesn't work. It doesn't work because the second line in our function isn't actually doing anything to change the output of your function. Your function right now is the same as:

def first_4(iter):
    return iter

If you want to actually return the first four characters, you need to do something like:

def first_4(iter):
    iter = iter[:4]
    return iter
#or 
def first_4(iter):
    return iter[:4]