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 Sagar Adhikari for List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

$
0
0

Python lists are mutable objects.

m = list([1, 2, 3])`n = ma = 5b = aid(a) == id(b)`# id() return "identity" of the object.# True,  Both a and b are references to the same object. id(m) == id(n)# True,  Both m and n are references to the same object. b = b + 2id(a) == id(b)# False, a new object on separate location is created, which b will point.n.pop()id(m) == id(n)# True, the object is mutated, and m and n still references to the same object.

Since, python lists are mutable, m and n will still be reference to the same object after mutation. Whereas, for immutable objects like int, a new object will be created and the identifier will refer to the new object.

Gist is, in your scenario, there has been only one object since python lists are mutable.

However, if you need the original list unchanged when the new list is modified, you can use the copy() method.

new_list = original_list.copy()

The ids of new_list and original_list is different.

Learn here about mutability in detail: https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747.


Viewing all articles
Browse latest Browse all 117

Trending Articles



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