2

I am assigning values to a nested matrix in a traditional for loop.

    matrix= [[0 for j in range(3)]for i in range(3)]
    value = 10
    # Setting a value to a particular row in the matrix
    for i in range(3):
        if i == 2:
            for j in range(3):
                matrix[i][j] = 10
    # Setting a value to a particular column in the matrix
    val  = 20
    for i in range(3):
        for j in range(3):
            if j == 1:
                matrix[i][j] = 20

Can assigning of the values to the matrix be done in a nested list comprehension? I did try this :

                matrix = [[value for j in i if j == col ]for i in matrix]

But it isn't modifying the matrix, instead creates a new one.How can I accomplish this with nested list comprehensions?

2
  • matrix[:] = [[value for j in i if j == col ]for i in matrix] would change the original list but I don't think your examples are the same Commented Jun 10, 2015 at 14:46
  • 1
    Have you tried using numpy? Commented Jun 10, 2015 at 14:54

2 Answers 2

4

Your example can easily be done using numpy arrays.

import numpy as np
matrix = np.zeros((3,3))

# Setting a row
matrix[1] = 10

# Setting a column
matrix[:,1] = 20
Sign up to request clarification or add additional context in comments.

Comments

0

The following comprehension does the job:

matrix= [
    [
        20 if j == 1 else 10 if i == 2 else 0
        for j in range(3)
    ]
    for i in range(3)
]

It will produce:

[[0, 20, 0], [0, 20, 0], [10, 20, 10]]

In your solution you don't have to do go through all cells twice.

matrix = [[0 for j in range(3)] for i in range(3)]
for i in range(3):
    matrix[2][i] = 10
    matrix[i][1] = 20

2 Comments

What if I would like to modify the existing matrix by assigning a value to a particular row? As far as i know,your solution(list comprehension ) just creates a new list.If I am wrong,please explain.
List comprehension I proposed is the only thing you should do (without matrix= [[0 for j in range(3)]for i in range(3)]). List comprehension will create list but that would be the only list you have to create. If you want just modification than look at the second part of the answer (with for loop).

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.