0

I was trying to assign values to multi dimension list in python after initializing it to zeroes first. Following is the code where edge_strength and initialProb are multiD list.

    edge_strength = [[1,2,3],[3,4,5],[6,7,8]]
    initialProb = [[0]*3]*3
    initialColumn =1
    denominator = 10
    for r in range(0,3):
        initialProb[r][initialColumn] = float(edge_strength[r][initialColumn])/denominator
    print initialProb

But when I finished and printed initialProb list, I got answer as - [[0, 0.7, 0], [0, 0.7, 0], [0, 0.7, 0]] Instead it should've been - [[0, 0.2, 0], [0, 0.4, 0], [0, 0.7, 0]].

Can anyone explain me this strange behaviour and the workaround?

Mihir Thatte
  • 105
  • 1
  • 2
  • 9

1 Answers1

0

I don't understand why you solution does not work either. It seems as if edge_strength[r][initialColumn] is broadcasted although initialProb[r][initialColumn] is a scalar. I would expect something similar if you instead wrote

initialProb[1] = float(edge_strength[r][initialColumn])/denominator

but like this it does not make sense.

Here is a workaround using numpy. numpy-arrays have the advantage, that multiple columns can be addressed at once. I hope that helps at least.

import numpy as np
initialProb = np.zeros((3,3))
edge_strength = np.array([[1,2,3],[3,4,5],[6,7,8]])
initialProb[:,initialColumn] = edge_strength[:,initialColumn].astype(np.float)/denominator

Edit: I understood what's going on. Refer to Python list multiplication: [[...]]*3 makes 3 lists which mirror each other when modified When you initialize initialProb you don't get three different rows, but three references to the same list. If you modify the list, all three are changed.

According to the thread

initialProb = [ [0]*3 for r in range(3) ]

should also solve your error

Community
  • 1
  • 1
maow
  • 2,712
  • 1
  • 11
  • 25