List manipulation in functions


#1



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

Oops, try again. list_extender([1, 2, 3, 4]) returned [1, 2, 3, 4, 9, 9] instead of [1, 2, 3, 4, 9]

It returns this error message in the work screen even though in the print screen, it shows the correct answer of [1, 2, 3, 4, 9]


Was looking for the answer of [1, 2, 3, 4, 9]


n = [1,2,3,4]
# Add your function here
def list_extender(lst):
    n.append(9)
    return n

print list_extender(n)


#2

what happens if we add another function call:

n = [1,2,3,4]
# Add your function here
def list_extender(lst):
    n.append(9)
    return n

print list_extender(n)
print list_extender([5,6,7])

the list should be extended to [5,6,7,9], but that is not happening.

Another way to explain this, if you gave me your script, and i wanted to import the list extender function from your script:

from your_script import list_extender

i will get an error, n is undefined

A function which only works for a single list or can't be imported into other scripts, is not really nice

How do you think we can fix this?
`


#3

Thanks, I have modified my code to the following:

n = [1,2,3,4]
# Add your function here
def list_extender(n):
    n.append(9)
    return n

print list_extender(n)

This now return the correct answer.
Are my modifications in line with correct methodology?


#4

yes, now it all works. You understand it as well?


#5

Can you please explain it? I don't understand. It asked for It to take a parameter of "1st". I'm confused although I see the code works.


#6

Hi,
It's not '1st' but 'lst' as in LST - abbreviation for list.


#7

here:

def list_extender(n):

you can make the function parameter lst, but then in the function you should append to lst

The most important thing to understand, is that the parameter is just a placeholder until you call the function and supply an argument:

# function call with argument n
print list_extender(n)

now the value of n will copied into the function parameter lst


#8

Thank you so much, it makes sense now.


#9