1

My teacher told me that purchase_list=my_list is passing by reference/address. For example:

my_list = ['pen' , 'pencil' , 'cell phone' , 'axiom team' , 'panacloud' ]
purchase_list = my_list
my_list.append('x')
print(my_list)
print(purchase_list)

gives the following output

['pen', 'pencil', 'cell phone', 'axiom team', 'panacloud', 'x']
['pen', 'pencil', 'cell phone', 'axiom team', 'panacloud', 'x']

then why is that when i do the following:

my_list = ['pen' , 'pencil' , 'cell phone' , 'axiom team' , 'panacloud' ]
purchase_list = my_list
my_list=["Naufil"]
print(my_list)
print(purchase_list)

gives me output:

['Naufil']
['pen', 'pencil', 'cell phone', 'axiom team', 'panacloud']

and doesn't

['Naufil']
['Naufil']
  • 1
    You're redefining what `my_list` is, you're not changing the value of what it was previous assigned to. `append` is an inplace operation. – Zain Patel Aug 17 '18 at 16:34
  • 1
    You need to understand the difference between names and values. An assignment like `my_list=["Naufil"]` binds a value to a name. `my_list.append('x')` mutates the list that's bound to the name `my_list`. They're two completely different operations. – Aran-Fey Aug 17 '18 at 16:38
  • @Aran-Fey So when i binded a value to my_list, shouldn't it be passed to the purchased_list too. Because purchased_list knows the address of my_list and no matter what functions I perform on my_list, should also happen with purchased_list? – Naufil Muhammad Aug 17 '18 at 16:55
  • No, binding a value to a name doesn't automagically rebind all other names that refer to the same value as well. Can you imagine the chaos? Say you have a variable `x = 0` and you set it to `x = 123`. Would you *really* want *all variables in the entire program* with the value 0 to be set to 123? – Aran-Fey Aug 17 '18 at 16:58
  • @Aran-Fey Would you really want all variables in the entire program with the value 0 to be set to 123?: Not all variables, but those variables should be changed from 0 to 123 who knows the address of x. Look purchase_list knows the address of my_list variable. – Naufil Muhammad Aug 18 '18 at 06:49
  • `x` doesn't have an address. Again, that's the difference between a name and a value. `x` is a name. 0 is the value, and every single 0 in a python program shares the same address. (At least in CPython) – Aran-Fey Aug 18 '18 at 07:15
  • Python is always pass-by-value, just like Java. There is never any pass-by-reference. – newacct Aug 23 '18 at 00:04

0 Answers0