0

This code:

import pprint
pp = pprint.PrettyPrinter()
matrix = [[None]*6]*6
ROWS = len(matrix)
COLS = len(matrix[0])
for row in range(ROWS):
    for col in range(COLS):
        matrix[row][col] = row+col
pp.pprint(matrix)

Prints this:

[[5, 6, 7, 8, 9, 10],
[5, 6, 7, 8, 9, 10],
[5, 6, 7, 8, 9, 10],
[5, 6, 7, 8, 9, 10],
[5, 6, 7, 8, 9, 10],
[5, 6, 7, 8, 9, 10]]

Whereas this code produces the desired result:

import numpy
import pprint
ROWS = 6
COLS = 6
matrix = numpy.zeros((ROWS,COLS))
for row in range(ROWS):
    for col in range(COLS):
        matrix[row][col] = row+col
pp.pprint(matrix)

And outputs this:

[[  0.,   1.,   2.,   3.,   4.,   5.],
[  1.,   2.,   3.,   4.,   5.,   6.],
[  2.,   3.,   4.,   5.,   6.,   7.],
[  3.,   4.,   5.,   6.,   7.,   8.],
[  4.,   5.,   6.,   7.,   8.,   9.],
[  5.,   6.,   7.,   8.,   9.,  10.]]

I thought I knew how multidemsional lists worked but I guess not. What could cause my code to be assigning the same values to every row in the list?

0 Answers0