0

I can't quite understand this behavior, but why in python3 the list.pop() method removes the object from the list as well as the copied list, what if I'd like to have the copy as the reference. MWE:

>>> a =['1','2','3']
>>> a
['1', '2', '3']
>>> b=a
>>> b.pop(0)
'1'
>>> b
['2', '3']
>>> a
['2', '3']
Amir
  • 1,348
  • 3
  • 21
  • 44

1 Answers1

1

The assignment of list a to b does not make a copy; they are still pointing to the same underlying list object.

If you want to make a full copy of the list you can just use slice notation to copy the full list:

>>> a =['1','2','3']
>>> b = a[:]
>>> b.pop(0)
'1'
>>> b
['2', '3']
>>> a
['1','2','3']

Or more generally, see the copy module

lemonhead
  • 5,328
  • 1
  • 13
  • 25
  • Interesting. However, this behavior does not happen when we modify the original list, say `a+1`. Does it relate to `pop()` or is it a general Python behavior? – Amir Dec 04 '20 at 05:38
  • 1
    @Amir: The behavior *does* happen in general when you modify the original (only) list. `a+1` is invalid for a list, but any actual modification would show up through both variables. – user2357112 Dec 04 '20 at 05:42
  • 1
    It's general Python behavior for mutable objects -- the same would happen if you were to modify the original list, say with with `a.append('4')`. Strings and ints are immutable and thus wouldn't exhibit this same behavior – lemonhead Dec 04 '20 at 05:43