0

I have an issue where when I append a 1D list multiple times as rows to a 2D list, subsequent changes to the 2D list affect all rows. This thread (Python list confusion) cleared up why this is the case - basically each row is the same sub-list or object so a change to that sub-list changes every row in the 2D list. However, I don't know how to fix it. Here is my example:

NumOfRows = 100
LanesToCheck = [0, 1, 2, 3]
Lanes = []
for j in range(0,NumOfRows):
    Lanes.append(LanesToCheck)

LanesToCheck is used to initialize each row and the idea is that the user of my script can just change this 1D list in an easy code location and the entire 2D array is initialized with it. I know I can just use:

Lanes.append([0, 1, 2, 3])

but I'd like to have this LanesToCheck constant easily accessible to the user. Is there a way to initialize my 2D array using this 1D array in a way that each row is a separate entity?

Community
  • 1
  • 1
alphaOri
  • 87
  • 3
  • 6

2 Answers2

2

Use this:-

Lanes = [LanesToCheck[:] for j in range(NumOfRows)] 
# makes copy of `LanesToCheck` every time.

you can use every row as a seperate entity by doing this,

Lanes[0][0] = 11

if you insert 11 to your 1st rows 1st column then other rows will remain unchanged.

ouput:-

[[11, 1, 2, 3], [0, 1, 2, 3], ...... and so on
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
-1
Lanes = [0,1,2,3] * NumOfRows

Very pythonic - but wrong :-(

Maybe, if you want to make it explicit that you're making copies of the list:

import copy
Lanes = [copy.deepcopy(LanesToCheck) for i in xrange(NumOfRows)]
emvee
  • 4,371
  • 23
  • 23
  • Maybe pythonic but does **not** answer question ! `[0,1,2,3] * 2` gives `[0,1,2,3,0,1,2,3]` 1D list instead of list of list. And even `[[0,1,2,3]] * NumOfRows` make use of the same instance of inner list : `x = [[0,1,2,3]] * 2` `x[0][0] = 11` gives `[[10, 1, 2, 3], [10, 1, 2, 3]]` – Serge Ballesta Nov 18 '14 at 09:44
  • 1
    You are right, sorry! – emvee Nov 18 '14 at 10:31