Column stack matrix in a for loop in Python

Viewed 64

I have some starter matrix A = [1,2,3,4] and I want to implement a loop that will apply a power to the starter matrix.

for i in range(3,0,-1)
    A**i

While this loop occurs, I also want to column stack the matrix as B = [[1,8,27,64],[1,4,9,16],[1,2,3,4],[1,1,1,1]]. How do I implement this?

1 Answers

Updated answer:

I think this code actually answers your question better (e.g. to use a generator matrix/row). The list comprehension logic doesn't change, all we're doing here is defining the x list rather than generating from a range.

starter_row = [1, 2, 3, 4]
num_rows = 4

result = [
    [x ** y for x in starter_row] for y in range(num_rows - 1, -1, -1)
]

print(result)

Output (same as below):

[[1, 8, 27, 64], [1, 4, 9, 16], [1, 2, 3, 4], [1, 1, 1, 1]]

Original answer:

You could do achieve this with list comprehension:

row_len = 4
num_rows = 4

result = [
    [x ** y for x in range(1, row_len + 1)] for y in range(num_rows - 1, -1, -1)
]

print(result)

Output:

[[1, 8, 27, 64], [1, 4, 9, 16], [1, 2, 3, 4], [1, 1, 1, 1]]

The benefit of this implementation is that you can adjust the dimensions on the fly as needed. If you always needed an X by X matrix, you could simplify a bit by just making one variable for the size, the list comprehension would stay the same.

Additionally if you wanted to reverse the order of the rows, you just change the y range generator to range(num_rows).

Related