-1

I need to create a list as a function of two variables, but the output from that list is different from the output from another list created manually (both list are equal).

Here is the code:

from math import factorial
n=4
k=3
ntuples=int(factorial(n-1)/factorial(k-1))
B=[[1]*k]*ntuples
A=[[1,1,1],[1,1,1],[1,1,1]]
print(A==B)
m=0
n=0
for i in range(len(A)):
    A[i][m]=A[i][m]+1
    m+=1
for j in range(len(B)):
    B[j][n]=B[j][n]+1
    n+=1
print(A)
print(B)

output:

True
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]

I want to get the output of A, but using B list. What am I doing wrong? Thanks!

cs95
  • 379,657
  • 97
  • 704
  • 746
immb31
  • 75
  • 1
  • 1
  • 6

1 Answers1

1

When u initialize a matrix like this: B=[[1]*k]*ntuples, all the other values will change if one value is changed. Here is a demonstration of it:

>>> B
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]

>>> B[0][0]
1

>>> B[1][0]
1

>>> B[0][0] = 0

>>> B[0][0]
0

>>> B[1][0]
0

>>> B[2][0]
0

>>> B
[[0, 1, 1], [0, 1, 1], [0, 1, 1]]

In order to avoid this, you can use numpy:

import numpy as np
B=np.ones((ntuples,ntuples),dtype = int)

Full code:

from math import factorial
n=4
k=3
import numpy as np
ntuples=int(factorial(n-1)/factorial(k-1))
B=np.ones((ntuples,ntuples),dtype = int)
A=[[1,1,1],[1,1,1],[1,1,1]]
print(A==B)
m=0
n=0
for i in range(len(A)):
    A[i][m]=A[i][m]+1
    m+=1
for j in range(len(B)):
    B[j][n]=B[j][n]+1
    n+=1
print(A)
print(B)

Output:

[[ True  True  True]
 [ True  True  True]
 [ True  True  True]]
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
[[2 1 1]
 [1 2 1]
 [1 1 2]]

If you don't wanna use numpy, then you can achieve the same result using lists too. Just replace B=np.ones((ntuples,ntuples),dtype = int) with the line below:

B=[[1,1,1] for x in range(ntuples)]

Output:

True
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
[[2, 1, 1], [1, 2, 1], [1, 1, 2]]
Sushil
  • 5,440
  • 1
  • 8
  • 26