Home > OS >  I have created a program to remove the columns of a matrix one by one after removing the first row o
I have created a program to remove the columns of a matrix one by one after removing the first row o

Time:10-28

i.e after i remove the first column of the matrix,i want to remove the second column while restoring the first one and then remove the third column while restoring the second one.However i am not able to do that so i need help

Expected output after each iteration of i:

[[5, 6], [8, 9]]

[[4, 6], [7, 9]]

[[4, 5], [7, 8]]

My code so far:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

b = []

b = a.copy()

a.pop(0)

for i in range(3):
    for j in range(2):
        a[j].pop(i)
    a = b

CodePudding user response:

First, you need to take your copy of b after you pop the top row, not before. Second, copy does create a new list, but the new list still contains references to the three old lists. You can either use deepcopy, or do it like this:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

a.pop(0)

b = [row[:] for row in a]

for i in range(3):
    for row in a:
        row.pop(i)
    print(a)
    a = [row[:] for row in b]
  • Related