0

What I want to do is to make a simple variable for complex code. For example,

list1 = [['apple','banana'], ['cat', 'dog']]
new = list1[0][1]
new = 'bonono'
print(list1[0][1])   # The result is 'banana', but I hope this to be 'bonono'

I don't want to type list1[0][1] every time, I just want to type new for the same value.
If this was C language maybe I can use pointer, but in python I can't find how.
I read about shallow copy or deep copy but it seems it's not about both. So copy.copy() also didn't work. Can anyone tell me how?

martineau
  • 119,623
  • 25
  • 170
  • 301
June Yoon
  • 433
  • 1
  • 3
  • 11
  • You are trying to use "new" as a pointer. Python does not have pointers. Also, as soon as new was given a new value it released the alias it held to the old value – Barak Friedman Oct 25 '20 at 16:51

2 Answers2

1

Python is a reference-based language and strings are immutable, so when when you set new = 'bonono', you are not changing the same object, you are referencing a different object.

You can do something like:

list1 = [['apple','banana'], ['cat', 'dog']]
new = list1[0][1] = 'bonono'

But you will have to be sure to replace the list entry every time.

Here is a little more detail to show you what's happening with the references:

>>> from sys import getrefcount
>>> list1 = [['apple','banana'], ['cat', 'dog']]
>>> getrefcount('banana')
# One ref in list, one in gc, one in getrefcount call
3
>>> new = list1[0][1]
>>> getrefcount('banana')
# One ref in list, one to new, one in gc, one in getrefcount call
4
>>> new = 'bonono'
>>> getrefcount('banana')
# One ref in list, one in gc, one in getrefcount call
3
>>> getrefcount('bonono')
3
# One ref to new, one in gc, one in getrefcount call
aviso
  • 2,371
  • 1
  • 14
  • 15
0

Python is based by reference, so when you set the value of new to anything else and you are referencing a different object, because strings are immutable. And python does not have pointers. So you can do like this each time you change the new value:

new,list[0][1] = 'bonno','bonno'
Wasif
  • 14,755
  • 3
  • 14
  • 34