0

As I have been told that when we pass a list to a function, the list is passed by reference.

So, if I have

>>> a = [0]
>>> def change(a):
...     a += [1]

The following works as expected.

>>> change(a)
>>> a
[0, 1]

But if I have the function change as

>>> def change(a):
...     a = [1]

and a = [0]. Then if I do,

>>> change(a)

The result is as following

>>> a
[0]

This means that here, the list was not passed by reference.

Is this behaviour expected? I am using Python 2.7.6

Himanshu Mishra
  • 8,510
  • 12
  • 37
  • 74
  • Reassignment is not the same as alteration. If you do `a = [1]` you are not altering a list; you are creating a new list. The old one is not altered. – khelwood Sep 07 '16 at 08:57
  • `a = b = [1];` Now doing `a = 2` won't affect `b`, `a` now points to a new object. – Ashwini Chaudhary Sep 07 '16 at 08:58
  • @AshwiniChaudhary Thanks for the comments. I still do not understand why are there two different variables if one is passed by reference to a function? – Himanshu Mishra Sep 07 '16 at 09:00
  • I shall take a look at the already existing question. – Himanshu Mishra Sep 07 '16 at 09:02
  • Because you just tell `a` to reference a different area of memory containing the array `[1]`. You do not update/overwrite the original array. – Phylogenesis Sep 07 '16 at 09:03
  • The variable `a` inside the definition of `change` is a different variable from the variable `a` outside the definition of `change`. To begin with, they are referring to the same list. Then you change the one inside `change` to refer to a different list. It would be clearer if you hadn't called them both `a`. – khelwood Sep 07 '16 at 09:47

0 Answers0