-3
def foo(a, b):
    a = 1
    b[0] = 2

p, q = 100, [200, 300]
foo(p, q)
print(p, q)

>>> 100 [2, 300]

My question is that, why q changes, but p does not? Thank you!

Wenting.W
  • 37
  • 6
  • Did you expect `b` to be copied? It's not, all names are references. See the duplicate on how this works. Or see [How to clone or copy a list?](//stackoverflow.com/q/2612802) to create a copy. – Martijn Pieters May 25 '17 at 11:08
  • Before putting your questions here, please search for the similar. There are too many similar questions, you can have answers from them – Jay Parikh May 25 '17 at 11:12
  • Thanks a lot. I have tried searching but used the wrong keywords. – Wenting.W May 25 '17 at 14:23

1 Answers1

1

q is a list therefore is "passed by reference" to the function. p is passed by value.

sophros
  • 14,672
  • 11
  • 46
  • 75