0

I make a 2D list:

list1 = []
liste = [0, 0, 0, 0, 0]
for i in range(93):
    list1.append(liste)

And then try to update the elements in one of them by:

stemmer_tall = [123, 3321, 3442, 23, 1]

for i in range(5):
    list1[0][i] += stemmer_tall[i]

When I do it, it updates not just the first list in my list, but all of them. What is wrong here? I cant figure it out.

EDIT: I want a list with 92 lists inside it, with just have zeroes. But the first list should be [123, 3321, 3442, 23, 1].

Gard
  • 11
  • 4
  • What is the expected output? What should the resulting list look like? – Ctrl S Nov 23 '18 at 13:49
  • Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – mkrieger1 Nov 23 '18 at 14:01

3 Answers3

1

You are adding the same reference to the list every time. So each item in list1 points to the same liste variable.

You could make a new copy of the array. It would look like this:

list1 = []
liste = [0, 0, 0, 0, 0]
for i in range(93):
    list1.append(liste.copy())

stemmer_tall = [123, 3321, 3442, 23, 1]
for i in range(5):
    list1[0][i] += stemmer_tall[i]
Wouter van Nifterick
  • 23,603
  • 7
  • 78
  • 122
0

You append the same list over and over again. In python, when you create a list as

liste = [0, 0, 0, 0, 0]

liste is essentially a reference to the list you just created. Then, when you append this reference over and over again to another list as

list1 = []
for i in range(93):
    list1.append(liste)

you append the same reference over and over again; but they all point to the same list. If you want to create different lists, then you should create different lists:

list1 = []
for i in range(93):
    list1.append([0]*5)

Now, if you change one of the lists, the others won't change.

eozd
  • 1,153
  • 1
  • 6
  • 15
0

There is no need to add each list element in stemmer_tall individually. You can simply assign it to the first list in list1:

list1 = []
liste = [0, 0, 0, 0, 0]
for i in range(93):
    list1.append(liste)

stemmer_tall = [123, 3321, 3442, 23, 1]
list1[0] = stemmer_tall

Output (Tested with Repl.it)

[123, 3321, 3442, 23, 1]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

(etc)

Ctrl S
  • 1,053
  • 12
  • 31