0

I was coding with Python and a bug made me notice this.

Say, I have this code:

class test1(object):
    def __init__(self):
        self.hello = ["hello"]
        self.text_back = test2().stuff(self.hello)
        print "With list:   ",self.hello[0], self.text_back[0]

class test2(object):
    def stuff(self,text1):
        self.asdf = text1
        self.asdf[0] = "goodbye"
        return self.asdf

a = test1()

#---------------

class test3(object):
    def __init__(self):
        self.hello = "hello"
        self.text_back = test4().stuff(self.hello)
        print "Without list:",self.hello, self.text_back

class test4(object):
    def stuff(self,text1):
        self.asdf = text1
        self.asdf = "goodbye"
        return self.asdf

b = test3()

The output is:

With list:    goodbye goodbye
Without list: hello goodbye

I have the identical code between the two, except that one is list and one isn't. Why am I getting different results?

Tetsudou
  • 224
  • 1
  • 14

1 Answers1

0

In code, we are not creating new variable for list, we just create reference variable name.

Demo:

>> l1 = ["hello"]
>>> l1= l1
>>> l2= l1
>>> id(l1), id(l2)
(3071912844L, 3071912844L)
>>> l1
['hello']
>>> l2
['hello']
>>> l2[0] = "goodbye"
>>> l2
['goodbye']
>>> l1
['goodbye']
>>> 

Normally copying a list:

>>> l1 = [1,2,3]
>>> l2 = l1[:]
>>> id(l1), id(l2)
(3071912556L, 3071912972L)
>>> l1.append(4)
>>> l1
[1, 2, 3, 4]
>>> l2
[1, 2, 3]
>>> 

Nested datastructures:

>>> l1 = [1,2, [1,2], [3,4]]
>>> l2 = l1[:]
>>> l1.append(4)
>>> l1
[1, 2, [1, 2], [3, 4], 4]
>>> l2
[1, 2, [1, 2], [3, 4]]
>>> l1[2].append(3)
>>> l1
[1, 2, [1, 2, 3], [3, 4], 4]
>>> l2
[1, 2, [1, 2, 3], [3, 4]]
>>> 

Deep copies in Python

>>> import copy
>>> l1 = [1,2, [1,2], [3,4]]
>>> l2 = copy.deepcopy(l1)
>>> l1.append(4)
>>> l1[2].append(3)
>>> l1
[1, 2, [1, 2, 3], [3, 4], 4]
>>> l2
[1, 2, [1, 2], [3, 4]]
>>> 

Link

Vivek Sable
  • 9,938
  • 3
  • 40
  • 56