0

Is this a bug of Python? I define a simple list: a = ['a', 'b', 'c', 'd'] I copy this list into another variable z: z = a I remove one element from the first list: a.remove('a') which produces ['b', 'c', 'd'] as expected. But then ask Python to display z too. The output is: ['b', 'c', 'd'] as well!? As if a and z are pointing to the same value, instead of being separate variables?

Fred
  • 1
  • 1
  • 1
    "Is this a bug of Python?" - 99.999999999999999999999999999% chance, no. – TigerhawkT3 May 05 '16 at 07:40
  • 1
    And on reading past that sentence, I see that your confusion stems from the belief that `z = a` makes a separate copy of a `list`. It does not. See the linked duplicate, and also [here](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python) for more. – TigerhawkT3 May 05 '16 at 07:42
  • 1
    You create a shallow copy. Meaning both your variables are aliases for the same list. To create a deep copy (both aliases point to their own list) you can use the 'copy.deepcopy()' from the 'copy' module. – fgoettel May 05 '16 at 07:47
  • 1
    @deloz - a shallow copy would be `z = a[:]` or `z = list(a)`. This is simply asigning a second name to the same list, no copying involved. – mata May 05 '16 at 08:06
  • Thank you... using `z = list(a)` solves that. Creating a "deep copy". – Fred May 06 '16 at 07:30

0 Answers0