Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I would like to invert the order of each matrix column as follows:

A = [[ 4,  8, 12, 16],

     [ 3,  7, 11, 15],

     [ 2,  6, 10, 14],

     [ 1,  5,  9, 13]]

The required result:

A = [[ 1,  5,  9, 13],

     [ 2,  6, 10, 14],

     [ 3,  7, 11, 15],

     [ 4,  8, 12, 16]]

As can be seen each column changed its order.

I use the following code for it:

B = [row[:] for row in A]

k = 0

for i in range(len(A), -1, -1):

    k = k + 1,

    for j in (range(len(A))):

        B[k, j] = A[i, j]

print(B)

However, I get the following error:

TypeError                                 Traceback (most recent call last)

<ipython-input-91-72c0a8d534ec> in <module>()

      9     k = k + 1,

     10     for j in range(len(A)):

---> 11         B[k, j] = A[i, j]

     12 

     13 print(B)

TypeError: list indices must be integers or slices, not tuple

1 Answer

0 votes
by (25.1k points)

You are getting this error because you are accessing the nested lists the wrong way, do it like this:

B[k][j] = A[i][j]

Not like this: B[k, j] = A[i, j]

Also your code seems to be unnecessarily complicated you can just do it like this:

A = A[::-1]

This would get you the required result.

Related questions

0 votes
1 answer
asked Jul 29, 2019 in Python by Rajesh Malhotra (19.9k points)
0 votes
1 answer
asked May 15, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...