1

Until recently, I thought Python passed parameters by value. For example,

def method1(n):
   n = 5
   return n

n = 1
m = method1(n)
>>> n == 5
>>> False

But if I pass in a list to a method, like

def method2(list):
   del list[0]
   return list

list1 = [0,1,2,3,4,5]
list2 = method2(list1)
>>> list1
>>> [1,2,3,4,5]

it mutates the list. I did another test:

l1 = ['a','b','c','d']
x = method1(l1)
>>> l1
>>> ['a','b','c','d']

Here the list did not change. My question is

Why do these different cases happen?

user217285
  • 346
  • 3
  • 16
  • here is a good explanation, http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference list is a mutable type – bro Jul 24 '15 at 06:36

1 Answers1

0

Python always passes by assignment , even in the first case, actually the object reference is passed. But when you do an assignment inside the function, you are causing the name to refer a new object. That would not mutate the name/variable that was used to pass the value to the function (Better explained in the below example).

Example -

>>> def func(n):
...     n = [1,2,3,4]
...     return n
...
>>> l = [1,2,3]
>>> func(l)
[1, 2, 3, 4]
>>> l
[1, 2, 3]

In your case, when you do del list[0] you are actually mutating the list in place (deleting the first element from it) , and hence it reflects in the place where the function was called from as well.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176