1

Whats the most efficient way to initialize a matrix in Python without using numpy. For example I'd like to create:

matrix = [
           [[0,0],[0,0],[0,0]]
           [[0,0],[0,0],[0,0]]
           [[0,0],[0,0],[0,0]]
         ]

I was creating one using:

dpcols = [[0,0]] * len(matrix[0])
matrix = [dpcols] * len(matrix)

But with this, if i change

matrix[1][1] = [1,1]

Then indexes [0][1], [1][1], and [2][1] all gets changed to [1,1], due to them all being linked together.

2
  • 2
    why the requirement of not using numpy? Commented Mar 15, 2017 at 20:28
  • Its just a restriction, cant use certain libraries Commented Mar 15, 2017 at 21:16

1 Answer 1

4

I don't think this is as efficient as numpy since it's a double for loop, but it's easy to write:

>>> rows,cols = 2,3
>>> a = [[[0,0] for c in range(cols)] for r in range(rows)]
>>> a
[[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]
>>> a[1][1] = [1,1]
>>> a
[[[0, 0], [0, 0], [0, 0]], [[0, 0], [1, 1], [0, 0]]]
Sign up to request clarification or add additional context in comments.

2 Comments

matrix = [[[0, 0] for _ in range(cols)] for _ in range(rows)] in his use-case
Was wondering if there are other ways without using 2 loops, but i guess this is the best i can do. Thanks for the help

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.