1

I wonder What is the difference between this two different method of 2D matrix initialization in python.

    m =[]
    K = []
    for x in range(0,W+1):
        m.append(0)
    for x in range(0,n+1):
        K.append(m)

and

    l = []
    for j in range(0,n+1):
        l.append([])
        for i in range(0,W+1):
            l[j].append(0))

when I tried to print l and K the both gave the same answer but when I tried to implement it in code the output of program changed.

the earlier one(K) gave an incorrect answer but later one(l) when implemented in the program gave a correct answer.

Mayank Joshi
  • 57
  • 1
  • 9

1 Answers1

1

In the first one, you are storing the same reference to list m in k. Change in m will be reflected in all the reference.

Where as in second, you are creating new lists in l. Hence, change in one is independent of another.

Alternatively, simpler way to initialize list is as:

  • Holding same reference to list (similar to your first approach) is as:

    >>> row, columns = 2, 3
    >>> my_list = [[0]*columns]*row
    >>> my_list
    [[0, 0, 0], [0, 0, 0]]
    >>> my_list[0][1] = 1  # changing value
    >>> my_list
    [[0, 1, 0], [0, 1, 0]]
    #    ^          ^ Reflected in all
    
  • Holding different reference to the list (similar to your second approach) is as:

    >>> my_list = [[0]*columns for i in range(row)]
    >>> my_list
    [[0, 0, 0], [0, 0, 0]]
    >>> my_list[0][1] = 1   # changing value
    >>> my_list
    [[0, 1, 0], [0, 0, 0]]
    #    ^  only one value is changed
    
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126