Learning python I was rewriting some of my old programs to see the
pros and cons of python when a steped in some weird (at least for me)
behavior.
Here it is simplified
The code:
myList = [4 for n in range(4)]
myInt = 4
[4, 4, 4, 4]
4
[4, 4, 4, 4]
4
[4, 4, 3, 4]
3
[4, 4, 3, 4]
4
I would not expect the second a.myList to have changed as it did
since, for me, I have only changed b.myList. And also, why only the
list changed and not the integer?
One thing i tried was:
myList = []
myInt = 4
def __init__(self):
self.myList = [4 for n in range(4)]
[4, 4, 4, 4]
[4, 4, 4, 4]
[4, 4, 3, 4]
[4, 4, 4, 4]
And as you see it worked as I expected.
Now the question, why?
pros and cons of python when a steped in some weird (at least for me)
behavior.
Here it is simplified
The code:
>>class Test1:
myInt = 4
>>a = Test1()
>>b = Test1()
>>a.myList
>>b = Test1()
>>a.myList
>>a.myInt
>>b.myList
>>b.myInt
>>b.myList[2] = 3
>>b.myInt = 3
>>b.myList
>>b.myInt = 3
>>b.myList
>>b.myInt
>>a.myList
>>a.myInt
I would not expect the second a.myList to have changed as it did
since, for me, I have only changed b.myList. And also, why only the
list changed and not the integer?
One thing i tried was:
>>class Test2:
myInt = 4
def __init__(self):
self.myList = [4 for n in range(4)]
>>a = Test2()
>>b = Test2()
>>a.myList
>>b = Test2()
>>a.myList
>>b.myList
>>b.myList[2] = 3
>>b.myList
>>b.myList
>>a.myList
And as you see it worked as I expected.
Now the question, why?
Comment