0
m,n=input().split( )
a=[[0]*int(n)]*int(m)

for i in range(0,int(m)):
  s=input().split()
  for j in range(0,int(n)):
    a[i][j]=int(s[j])

print(a)

I wanted to input this info for creating a 2D list:

3 4
11 12 13 14
21 22 23 24
31 32 33 34

however, the result is:

31 32 33 34
31 32 33 34
31 32 33 34
quamrana
  • 37,849
  • 12
  • 53
  • 71
Peter W
  • 1
  • 1
  • Could you provide your input as well? – yassadi Apr 17 '18 at 09:55
  • 3 4 for m and n//// and then 11 12 13 14 for a row – Peter W Apr 17 '18 at 09:57
  • And what is your preferred output? – yassadi Apr 17 '18 at 09:59
  • I'm sure you are not initialising your list properly. You end up with a list with lots of references to just one list. – quamrana Apr 17 '18 at 09:59
  • I initiated the a list by a=[] and changed the line " a[i][j]=int(s[j])" by "s[j]=int(s[j]) and a.append(s)". Then it works properly. Could you explain the reason? Thanks – Peter W Apr 17 '18 at 10:01
  • Your change works because each `s` is a brand new list and you add each of those to `a`. This means that each element of `a` is now a different list, whereas before `a` was filled with several references to the same list. (See https://nedbatchelder.com/text/names.html) – quamrana Apr 18 '18 at 08:06

0 Answers0