List manipulation in functions | Lists and Functions


#1

Hi, I'm getting stuck here in this exercise.

my code:-

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

On execution, it gives an syntax error on line 3(the function header line). I don't know what am I doing wrong. Help please :smiley:

Thanks


#2

n = [3, 5, 7]

Add your function here

def list_extender(lst):
lst.append(9)
return lst
print list_extender(n)

Hey, this is the right code. The task says you should append to lst not to n, which also confused me first. Also you have to return lst then. I would also love to get a explanation why we have to append it to lst and not to n.


#3

@tagblaster36627 oh, thanks for the solution :smiley: Cheers


#4

The function, list_extender, has a parameter, lst. When the function is called, as in the following statement, it extends and returns whatever list is passed to it as an argument ...

print list_extender(n)

When the above call is made, a reference to the list, n, is passed to the function parameter, lst, and the statements within the function are able to operate on that list by referring to it as lst.

Because the function is written to work with its parameter, lst, instead of only with the global list, n, you can use it to extend multiple lists, as follows ...

x = [3, 6]
y = [7, 8]
z = [11, 10]
print list_extender(x)
print list_extender(y)
print list_extender(z)

In each case, the argument used in the function call is assigned to the function parameter, lst, enabling the function to work on that list.


#5

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