4

What is the easiest way to construct a zeros matrix with a cardinality of 1000 (row) x 10 (column) in Python without using numpy? (just the standard library)

Also, say if I get a list of values with 10 elements. say a=[1 2 3 ... 10], and I would like overwrite the 1st row of the zeros matrix with this list a. How would I go about doing it.

Many thanks.

PS: the reason that I would like to use the normal python list rather than numpy to construct the matrix is because of the requirement of this assignment, which does not allow any external libraries other than the python standard lib.

C. Zeng
  • 635
  • 1
  • 8
  • 10
  • 2
    You might already be aware of this, but to future readers of the question who may not: You need to have a *very* good reason for using pure python lists over `numpy` arrays if you're doing many matrix operations, because built-in lists are very slow, space-inefficient, and cumbersome in comparison. – jme Jan 24 '15 at 04:25
  • Thanks @jme, I will clarify it in the question. This is for a coding assignment which prohibits me from using other non-standard libraries. I think numpy will be a better choice in most cases. – C. Zeng Jan 24 '15 at 05:09
  • @jme Sometimes a course or some other requirement may dictate not using third-party libraries. For example (and the reason I'm here), is that the AI course on edX says you can't use any third-party libraries (i.e. numpy) to implement a sliding puzzle solver. You can imagine how difficult this is without numpy! – Evan Zamir Feb 21 '17 at 21:37

1 Answers1

9

You can do:

m = [[0 for _ in range(10)] for _ in range(1000)]
m[0] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note that if you use:

>>> matrix = 3*[3*[0]]
>>> matrix 
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

after changing one element:

>>> matrix[0][0] = 1
>>> matrix
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

the whole column will change. So you should use this method only if you don't need your elements to be able to change independently.

elyase
  • 39,479
  • 12
  • 112
  • 119