Mike Kennard
Mike Kennard

Reputation: 1

Error when modifying list in python

I have had a problem when trying to change a specific item that is in a nested list.The code I have written is in python 2.7. This is what i have written:

list_1 = []
list_2 = []
infin = 25
while infin != 0:
    list_1.append((0,0,0))
    infin = infin - 1
infin = 5
while infin != 0:
    list_2.append(list_1)
    infin = infin - 1

Basically it makes a list that looks like this:

[[25 tuples],[25 tuples],[25 tuples],[25 tuples],[25 tuples]]

then when i attempt to modify the list by doing this:

list_2[0][0] = (1,1,1)

Every single list with 25 tuples in it will have (1,1,1) at the start, not just the first. Why?

Upvotes: 0

Views: 131

Answers (3)

AJNeufeld
AJNeufeld

Reputation: 8695

list_1 is a object. You then add the object to another list 5 times, creating not 5 copies of the object, but 5 references to the same object.

You need to copy the list as you create the second list:

infin = 5
while infin != 0:
    list_2.append(list(list_1))
    infin = infin - 1

Upvotes: 1

Munchhausen
Munchhausen

Reputation: 450

Because you are appending the same list list_1 5 times. What you change in list_1 is printed 5 times, because the list has been added 5 times. If you want new lists, use:

list(list_1)

Upvotes: 2

Bill
Bill

Reputation: 493

You're not actually appending different instances of lists, instead you're repeatedly appending a reference to the same list. Use list to avoid this.

list_1 = []
list_2 = []
infin = 25
while infin != 0:
    list_1.append((0,0,0))
    infin = infin - 1
infin = 5
while infin != 0:
    list_2.append(list(list_1))
    infin = infin - 1

Upvotes: 1

Related Questions