pirox22
pirox22

Reputation: 922

Strange behaviour when changing value of list in a list

While coding on a python project I noticed a strange behavior when I tried to change the value of a list in another list.

Not working code:

lst = []
to_add = [None,None,None]

for i in range(3):
    lst.append(to_add)

for i in range(3):
    lst[i][0] = anotherslistoflists[i][0]

To my surprise this example gave unexpected results. To be specific, every lst[i][0] got assigned with the same value which was the first element from the last index of the "anotherlistoflists" list.

Result example (when printing lst)

("word1",None,None)
("word1",None,None)
("word1",None,None)

Working code:

lst = []

for i in range(5):
    lst.append([None,None,None])

# same code as above

Result example2 (expected result)

("word1",None,None)
("word2",None,None)
("word3",None,None)

Of course, as you can see the problem is solved but I was wondering why the first code does not work. Something is probably wrong with the "to_add" list but I don't understand what is the problem here.

Upvotes: 0

Views: 92

Answers (3)

Mureinik
Mureinik

Reputation: 311188

You are appending the same list, to_add, three times. Then, once you modify it, all three items which point to it will reflect the same change. If you want to create a new copy with the same values, you could use the built-in list function:

for i in range(3):
    lst.append(list(to_add))

Upvotes: 1

Eric Renouf
Eric Renouf

Reputation: 14500

In the first case you are not adding a copy of add_to_list you are actually adding that exact list over and over, so when you change it later you're changing the real add_to_list and everywhere that refers to it. In the second case you're adding a new list containing None each time, and modifying different lists each time through

Upvotes: 0

dting
dting

Reputation: 39287

You are adding the same list, to_add to lst:

>>> a = [None]
>>> b = [a]
>>> c = [a]
>>> print a, b, c
[None] [[None]] [[None]]
>>> a[0] = 1
>>> print a, b, c
[1] [[1]] [[1]]

Upvotes: 0

Related Questions