I want to add the 1st element of each sublist with the values of another list
s1 = input() s2 = input() n1 = len(s1) n2 = len(s2) T = [[0]*n1]*n2 T[0] = list(range(n1)) for i in range(1,n2): T[i][0] = i print(T)
Output (comming):
[[0, 1, 2, 3, 4, 5], [5, 0, 0, 0, 0, 0], [5, 0, 0, 0, 0, 0], [5, 0, 0, 0, 0, 0], [5, 0, 0, 0, 0, 0], [5, 0, 0, 0, 0, 0]]
Output (want):
[[0, 1, 2, 3, 4, 5], [1, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0], [5, 0, 0, 0, 0, 0]]
Advertisement
Answer
Here let me tell you what is happening in your code…
T = [[0]*n1]*n2
In this line you made a nested list in which all the sublists are pointing to the same sublist in memory.
T[0] = list(range(n1))
In this line you now made your first sublist to point to a newly created list in memory. So thats why in the output the first list is same and not affected by the loop.
for i in range(1,n2): T[i][0] = i
Here all the other sublists (1,5) are being edited because they are pointing to the same elements.
So the solution would be: To declare your list like this :
T = [[0]*n1 for i in range(n2)]
This way each sublist is pointing to a different sublist. Hope this answer helps.
Happy coding!