I want to add the 1st element of each sublist with the values of another list
JavaScript
x
13
13
1
s1 = input()
2
s2 = input()
3
4
n1 = len(s1)
5
n2 = len(s2)
6
7
T = [[0]*n1]*n2
8
T[0] = list(range(n1))
9
for i in range(1,n2):
10
T[i][0] = i
11
12
print(T)
13
Output (comming):
JavaScript
1
2
1
[[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]]
2
Output (want):
JavaScript
1
2
1
[[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]]
2
Advertisement
Answer
Here let me tell you what is happening in your code…
JavaScript
1
2
1
T = [[0]*n1]*n2
2
In this line you made a nested list in which all the sublists are pointing to the same sublist in memory.
JavaScript
1
2
1
T[0] = list(range(n1))
2
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.
JavaScript
1
3
1
for i in range(1,n2):
2
T[i][0] = i
3
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 :
JavaScript
1
2
1
T = [[0]*n1 for i in range(n2)]
2
This way each sublist is pointing to a different sublist. Hope this answer helps.
Happy coding!