I'm trying to initialize a 2-D list using list comprehensions, but I'm seeing different results in Python 2 vs. Python 3 and I have no idea why. Sample code (the import
is just so I can use v3 print statements in v2):
from __future__ import print_function
ROW = 3
COL = 3
myList = [0 for i in range(ROW)]
#print('myList1 =', myList, 'len =', len(myList))
for i in range(len(myList)):
#print('i =', i)
myList[i] = [-1 for i in range(COL)]
#myList[0] = [-1 for i in range(COL)]
print('myList2 =', myList)
Python 3 output: myList2 = [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
Python 2 output: myList2 = [0, 0, [-1, -1, -1]]
The Python 3 behavior is what I would expect, and the commented out print statements are what I used to confirm that everything between the two up until the myList[i]
assignment is the same. If I manually do, e.g., myList[0] =...
outside of the for loop it updates that element as expected. What am I missing here?