Reputation: 333
My question is whether a function is can have the list method extend used on it? An example of the function in which I'm trying to understand:
def g(p):
w = p.pop(1)
p.extend(w)
return p
y = ['k', 'l', 'm']
g(y[:]).extend(g(y))
This returns the following value for y:
['k', 'm', 'l']
However I was expecting the following value for y:
['k', 'm', 'l', 'k', 'm', 'l']
Is someone able to explain to me what is happening here? Are functions not allowed to be used as an argument or are they also not allowed to have the list method extend used on them?
Upvotes: 1
Views: 76
Reputation: 36662
It works as intended:
What is going on, is that:
1- first, y is not mutated, since you are passing a deep copy of it to g
.
2- g is mutated when you pass it directly for the second call to g
3- you are not assigning the returned result from g(y)
4- extend returns None
def g(p):
w = p.pop(1)
p.extend(w)
return p
y = ['k', 'l', 'm']
res = g(y[:]) # <- this does not mutate y
res.extend(g(y)) # <- this does mutate y
y, res
result from the first call to g
|------------|
(['k', 'm', 'l'], ['k', 'm', 'l', 'k', 'm', 'l'])
|------------| |------------|
y mutated at 2nd call extended with mutated y from 2nd call
Upvotes: 1