0

I would like to know if this is normal behavior for Python. Code is:

>>>abcd = [["a","b","c","d"],[1,2,3,4]]
>>>testlist = []

then

>>>testlist.extend(abcd)

or if I use:

>>>for item in abcd:
    testlist.append(item)

the result of calling testlist is the same, which is perfectly fine:

>>>testlist
[['a', 'b', 'c', 'd'], [1, 2, 3, 4]]

but then when I do something with 'testlist' the change appears also in 'abcd'

>>>testlist[0].append("anything")
>>>testlist
[['a', 'b', 'c', 'd', 'anything'], [1, 2, 3, 4]]
>>>abcd
[['a', 'b', 'c', 'd', 'anything'], [1, 2, 3, 4]]

It is making me crazy. How should I proceed without changing original list and not making copies of it every time I need to pull some data from it. Thank you.

marek_25
  • 1
  • 1
  • 1
    There's only one list object. You're never making a copy of your list. Putting it into another list doesn't create a copy of it. – deceze May 29 '20 at 07:03
  • You have to distinguish between deep and shallow copies. In your case testlist seems to be a shallow copy, as changes to one are reflected also in the other. Thus, you might want to look into deep copying list. – Imago May 29 '20 at 07:04
  • This link might help you more in understanding different ways for copying list in python. https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – apoorva kamath May 29 '20 at 07:05

1 Answers1

1

You have to distinguish between deep and shallow copies. In your case testlist seems to be a shallow copy, as changes to one are reflected also in the other. Thus, you might want to look into deep copying list.

For example:

import copy
testlist = copy.deepcopy(abcd)

or even simpler:

testlist = abcd[:]
Imago
  • 521
  • 6
  • 29