Python Forum

Full Version: An array "mystery": The same array, the same operations but different outcomes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wrote the following code, where two identical arrays h and h1 are defined in different ways.
Then I produce the same operations on them and print the modified arrays. To my surprise, the outcome is different. The outcome for h1 is what I was expecting for both.

Please help me to understand why.

Here is the code:
    l1=3
    l2=3
    
    h=l1*[l2*[0]] 
    
    h1=[[0, 0, 0], [0, 0, 0], [0, 0, 0] ]

    print(h==h1)
    
    
#operations on array h   
    
    for i in range(3):
        for j in range(3):
            
                
            if i==0: 
                h[0][0]=1
                
                
            elif j==0: 
                h[i][j]=99
                
            else: pass
        
    print(h)
#IDENTICAL operations on array h1
    for i in range(3):
        for j in range(3):
            
                
            if i==0: 
                h1[0][0]=1
                
                
            elif j==0: 
                h1[i][j]=99
                
            else: pass
        
    print(h1)
    
#QUESTION: Why print(h) and print(h1) result in different arrays, when the initial
# arrays and the operations on them are the same ?

The outcome:

True
[[99, 0, 0], [99, 0, 0], [99, 0, 0]]
[[1, 0, 0], [99, 0, 0], [99, 0, 0]]
The initial arrays are not the same. The first one creates a list, then puts several references to that list in another list. There's only two list objects here, the inside one and the outside one. If the inside list is modified, all three references to it are changed.

The second list creates 3 separate interior lists and puts them all in another list. There are four separate list objects that are independent. Changing one doesn't affect the others.

>>> h = 3 * [3*[0]]
>>> print([id(x) for x in h])
[4327610368, 4327610368, 4327610368]   # 3 references to the same object
>>> h1 = [[0,0,0], [0,0,0], [0,0,0]]
>>> print([id(x) for x in h1])
[4328654144, 4328656704, 4328678144]   # 3 different objects
(Feb-17-2021, 06:20 PM)bowlofred Wrote: [ -> ]The initial arrays are not the same. The first one creates a list, then puts several references to that list in another list. There's only two list objects here, the inside one and the outside one. If the inside list is modified, all three references to it are changed.

The second list creates 3 separate interior lists and puts them all in another list. There are four separate list objects that are independent. Changing one doesn't affect the others.

>>> h = 3 * [3*[0]]
>>> print([id(x) for x in h])
[4327610368, 4327610368, 4327610368]   # 3 references to the same object
>>> h1 = [[0,0,0], [0,0,0], [0,0,0]]
>>> print([id(x) for x in h1])
[4328654144, 4328656704, 4328678144]   # 3 different objects
I can see now. Thank you!!