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.

3
  • 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. Commented Jan 24, 2015 at 4: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. Commented Jan 24, 2015 at 5: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! Commented Feb 21, 2017 at 21:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @elyase. This is a very thorough explanation :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.