1

I'm attempting to increment the values in a 2d array for a game I'm making, but I'm getting the same value in each array instead. This is the code:

def matrix(grid):

    nrows = len(grid)
    ncols = len(grid[0])

    for i in range(nrows):
        for j in range(ncols):
            grid[i][j] += 10

    for row in grid:
        print(row)

rows = 4
cols = 4
grid = [[0 for i in range(cols)] for i in range(rows)]
matrix(grid)

The output is:

[10, 10, 10, 10]
[10, 10, 10, 10]
[10, 10, 10, 10]
[10, 10, 10, 10]

Where as I would like it to be

[10, 20, 30, 40]
[10, 20, 30, 40]
[10, 20, 30, 40]
[10, 20, 30, 40]

Also, is it possible to stagger and use two nested for loops to provide incremented values for each row? Such as:

[10, 20, 30, 40]
[20, 40, 60, 80]
[10, 20, 30, 40]
[20, 40, 60, 80]
0

5 Answers 5

5

The output is as expected: the following line of code adds 10 to each cell, and since each is zero on entry, it becomes 10 in output

for i in range(nrows):
    for j in range(ncols):
        grid[i][j] += 10

Maybe the following would do, depending on what you are trying to do

for i in range(nrows):
    for j in range(ncols):
        grid[i][j] += 10*(j+1)

And for the two-loop version (not the output you give, but I didn't find the pattern)

for i in range(nrows):
    for j in range(ncols):
        grid[i][j] += 10*(i+j+1)
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to SO, Nice answer!
1

You might try this loop:

for i in range(nrows):
    for j in range(ncols):
        if (i % 2 != 0):
            grid[i][j] += 20*(j+1)
        else:
            grid[i][j] += 10*(j+1)

for the output:

[10, 20, 30, 40]
[20, 40, 60, 80]
[10, 20, 30, 40]
[20, 40, 60, 80]

1 Comment

Interesting, exactly what I was looking for.
1

Whenever you have to modify the whole list, try to do this with comprehensions. It is efficient. So, your problem can be solved with list comprehensions like this

rows = 4
cols = 4
grid = [[0] * cols for _ in range(rows)]
print [[(i * 10) for i in xrange(1, len(row) + 1)] for row in grid]

Output

[[10, 20, 30, 40], [10, 20, 30, 40], [10, 20, 30, 40], [10, 20, 30, 40]]

Comments

0

You need to change your code to:

for i in range(nrows):
    val = 10
    for j in range(ncols):            
        grid[i][j] = val
        val += 10

1 Comment

Or simply grid[i][j] = 10*(j+1)
0
def matrix(grid):

nrows = len(grid)
ncols = len(grid[0])
grid[0][0]=10;
for i in range(nrows):
    for j in range(ncols):
if(j!=0)
      grid[i][j] = grid[i][j-1]+10;
else 
grid[i][j]=10;

for row in grid:
    print(row)

Comments

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.