1. Lists manipulation in function


#1


https://www.codecademy.com/courses/python-beginner-nzzVa/2/4?curriculum_id=4f89dab3d788890003000096


### why does this work ###

def list_extender(lst):
    lst.append(9)
    return lst
    
n = [3, 5, 7]

print list_extender(n)

### and this not? ####

def list_extender(lst):
    lst = lst.append(9)
    return lst
    
n = [3, 5, 7]

print list_extender(n)


#2

because append() is a method which will modify the original list, but doesn't return anything. So the default (None) is returned. Which you store in a variable. We can demonstrate this:

def example():
    print "this function doesn't return anything"

x = example()
print x

see how x contains None? (the default that methods and function return)

in case of append, because you store it in the same variable, the list is overwritten with None


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.