Abo
Abo

Reputation: 69

how to fill matrix using range without numpy?

I created a matrix of zeros using lists, and I want to fill it based on matrix size, but I want the numbers to come sequentially.

I tried the following

matrix = []
for i in range(3):
    a =[]
    for j in range(3):
        a.append(i+j)
    matrix.append(a) 

I get this:

[[0, 1, 2], [1, 2, 3], [2, 3, 4]]

but the expected is:

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

thanks

Upvotes: 2

Views: 651

Answers (3)

Vincent Nagel
Vincent Nagel

Reputation: 73

You could multiply i by 3 like so:

matrix = []
for i in range(3):
    a =[]
    for j in range(3):
        a.append(3*i + j)     <-----
    matrix.append(a) 

Upvotes: 0

Hans Musgrave
Hans Musgrave

Reputation: 7131

Tagging on to @ShadowRanger's answer, rather than appending you can use a list comprehension if you would like.

dim = 3
matrix = [list(range(i, i+dim)) for i in range(0, dim**2, dim)]

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155458

Have your outer range loop with a step to provide the base value for each level. In this case, just change:

for i in range(3):

to:

for i in range(0, 9, 3):

It might be slightly more readable to phrase it in terms of a named variable like dim (for "dimension"):

dim = 3
for i in range(0, dim ** 2, dim):
    a = []
    for j in range(dim):
        a.append(i+j)
    matrix.append(a) 

Upvotes: 2

Related Questions