0

I fail to understand one of the result of this code – and especially what should I do as a "workaround":

#!/usr/bin/env python

a = [1, 2, 3]
b = a

print (a)    # >> gives [1, 2, 3]    # >> expected
print (b)    # >> gives [1, 2, 3]    # >> expected

b.clear()

print (a)    # >> gives []    # >> ??
print (b)    # >> gives []    # >> expected

Q1: Why is a also cleared ?

Q2: What should I do if I want to keep a as a sort of "template", so that, once set, do operations/modifications only on copies of it, without care about affecting the "original" in any way ?

(happens the same if a is a dictionary; happens the same if using del b[:] instead of b.clear())

secarica
  • 597
  • 5
  • 18
  • 3
    You didn't make a copy, you only created an additional reference. See the duplicate on how to properly copy a list. – Martijn Pieters Nov 29 '15 at 18:33
  • 1
    b=a only passes the reference of a to b; which means b and a both really point to the same list. Any operation you do on a will also be reflected upon b. To make b independent of a, you need to deep copy a so... b= list(a). Then all your changes to b and a will be independent – labheshr Nov 29 '15 at 18:33
  • Well, now I see the q/a there. That question uses other words and this is why I didn't found it using my own. What should I do now with my question ? Delete it ? – secarica Nov 29 '15 at 18:38

0 Answers0