Skip to content Skip to sidebar Skip to footer

List Index Changes Multiple Elements

I couldn't find anything matching my problem, so hopefully this wasn't already mentioned somewhere and I'm just too stupid to find it. thelist = [] a = [0] for i in range(5): t

Solution 1:

When creating thelist, it's saving a reference to the same object (a) in each position. When you append to the first element, it's actually appending to a in all the "thelist" slots. What you need to do is a deep copy on the object during construction:

thelist = []
a = [0]
for i in range(5):
    thelist.append(list(a))
print(thelist)

Then the following append will work as desired.

Solution 2:

a is an object that every item in the list is pointing to.

If you want every item in the list to be a different object (with the same value), you should create a new object before assigning it. the easiest way would be to do:

for i in range(5):
    thelist.append(list(a))

The list function receives a list and return a new instance with the same inner values. So you won't be changing the entire array every time.

Solution 3:

thelist and a both are lists. So, inside the for loop you are appending a list into another list

Case 1: a is a list

thelist = []
a = [0]
for i in range(5):
    thelist.append(a)
print(thelist)

[[0], [0], [0], [0], [0]]

Case 2: a is not a list but variable

thelist = []
a = 0for i in range(5):
    thelist.append(a)
print(thelist)


[0, 0, 0, 0, 0]

Post a Comment for "List Index Changes Multiple Elements"