2

I have a list of lists, where I duplicate a list element and if I adjust the initial element, the newly created element is also amended.

Is this a bug?

alfa = [[1,2,3,4],[5,6,7,8]]
alfa.append(alfa[0])
alfa[0].insert(0, 'a')

Even though I only incert 'a' in the first element of the list alfa, this is also added in the third element.

How can I avoid that?

Thanks

Thanasis
  • 695
  • 1
  • 4
  • 17

2 Answers2

2

you are appending a reference of the alfa[0] so any change in the appended list will be reflected also in the initial alfa[0], you can fix this by appending to your list alfa a copy of the list alfa[0]:

alfa.append(alfa[0].copy())
alfa[0].insert(0, 'a')
# [['a', 1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]
kederrac
  • 16,819
  • 6
  • 32
  • 55
1

When you append alfa[0] to alfa, you append a reference of the first item to alfa. So first and last items are the same object. So modifying the first or the third item, will change both.

Instead of appending a reference, you need to append an new object which is a copy of the first object. Example :

alfa = [[1,2,3,4],[5,6,7,8]]
# Magic is `list()`:
alfa.append(list(alfa[0]))
alfa[0].insert(0, 'a')
# Give: [['a', 1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]

A far better explanation: How to clone or copy a list?

Eric Frigade
  • 128
  • 6