Reputation: 71
def do_something(a, b):
a.insert(0, 'z')
b = ['z'] + b
a = ['a', 'b', 'c']
a1 = a
a2 = a[:]
b = ['a', 'b', 'c']
b1 = b
b2 = b[:]
do_something(a, b)
Why does a
give ['z' 'a' 'b' 'c']
while b
gives ['a' 'b' 'c']
?
I thought because they're same types they should merge.
Upvotes: 1
Views: 19
Reputation: 111219
b = ['z'] + b
creates a new list and makes the local variable b
point to it. The original list is not modified.
In contrast, the insert
method changes the existing list, so its effects can be seen outside of your function.
Upvotes: 1