0

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]]
  • 3
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Ch3steR May 06 '20 at 17:09

2 Answers2

1

The problem is how you create the T list - T[0], T[1], ... all contain a reference to the same list. By doing T[0] = list(...) you change the 0-th element to a new list, but all the rest remain the same. The correct way to initialize T is:

T = [[0 for _ in range(n1)] for _ in range(n2)]

abel1502
  • 955
  • 4
  • 14
1

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!

DETSUP
  • 107
  • 6