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 Ravi Shankar for List changes unexpectedly after assignment. Why is this and how to prevent it?

$
0
0
new_list = my_list[:]

new_list = my_listTry to understand this. Let's say that my_list is in the heap memory at location X i.e. my_list is pointing to the X. Now by assigning new_list = my_list you're Letting new_list pointing to the X. This is known as shallow Copy.

Now if you assign new_list = my_list[:] You're simply copying each object of my_list to new_list. This is known as Deep copy.

The Other way you can do this are :

  • new_list = list(old_list)
  • import copynew_list = copy.deepcopy(old_list)

Viewing all articles
Browse latest Browse all 117

Trending Articles



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