-1
>>> lista=[[12,13],[0,1]]
>>> lista
[[12, 13], [0, 1]]
>>> lista[0]=lista[1]
>>> lista
[[0, 1], [0, 1]]
>>> lista[0][0]+=10
>>> lista
[[10, 1], [10, 1]]

What i expect to happen is to last output be like:

 [[10, 1], [0, 1]]

but instead it behaves as if I typed:

lista[0][0]+=10 
lista[1][0]+=10

instead of just

lista[0][0]+=10

i think the problem is with this part:

lista[0]=lista[1]

because when i type instead

 lista[0]=list(lista[1])

it works just fine. Why is that?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Ratiel
  • 85
  • 7

2 Answers2

1

This is because lists in python are mutable

Essentially when you do:

lista[0]=lista[1]

You are saying let the index 0 point to the same location in memory that the index 1 is pointing to. So, we essentially have the same pointer at index 0 and 1 pointing to the same object.

A visual explanation:

Picture the list:

list_a = [1, 2, 3]

If we set list_b equal to list_a (by doing list_b = list_a) then we get can picture the lists as: Python lists sharing the same objects in memory

As you can see from above, the objects (the integers in list_a) are shared with list_b. Thus, if we change a value in list_b like so:

list_b[0] = 100 then list_a and list_b will look like [100, 2, 3]

Thus, if you apply this concept to your 2D list (table) you can picture we can observe that you are editing the same object in memory. In order to get your expected output you need to copy the list so that it points to its own unique object in memory.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • This is not "due to a concept known as mutability", just to the fact - that you otherwise explain - that in Python assignment doesn't copy the assigned object. – bruno desthuilliers Sep 21 '18 at 10:21
0

The problem is lista[0]=lista[1]. Assignment makes to objects refer to the same object, it does not copy them. eg, for two standalone lists

l1 = [1,2]
l0 = l1
l0[0] = 2 # print l1 after that

The exact same thing happens in your case.

However, list(lista[1]) creates a new list from the elements of lista[1], and assigns this new list to lista[0]. So now, they are two different objects, which happen to have the same values. If you change one, nothing happens to the other.

It would be the same if you used any other copying method, eg

lista[0] = lista[1][:]
blue_note
  • 27,712
  • 9
  • 72
  • 90