Quantcast
Channel: How do I clone a list so that it doesn't change unexpectedly after assignment? - Stack Overflow
Viewing all articles
Browse latest Browse all 117

Answer by bterwijn for How do I clone a list so that it doesn't change unexpectedly after assignment?

$
0
0

To understand the different Python clone/copy options have a look at this code that "copies" a nested list three different ways and uses memory_graph to graph the result:

import memory_graph as mg # see link above for install instructionsimport copya = [ [1, 2], ['x', 'y'] ] # a nested list (a list containing other lists)# three different ways to make a "copy" of 'a':c1 = ac2 = copy.copy(a) # equivalent to:  a.copy() a[:] list(a)c3 = copy.deepcopy(a)mg.show(locals()) # show the graph
  • c1 is an assignment, nothing is copied, all the values are shared
  • c2 is a shallow copy, only the value referenced by the first reference is copied, all the underlying values are shared
  • c3 is a deep copy, all the values are copied, nothing is sharedgraph of three different "copies"

Full disclosure: I am the developer of memory_graph.


Viewing all articles
Browse latest Browse all 117

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>