Friday, June 8, 2018

Python - Paying attention when you want to copy/clone a list

if you do b = a,

you didn’t copy the list referenced by a. You just created a new tag and attached it to the list pointed by a. Like in the picture below:
a and b reference the same list
If you modify a, you also modify b, since they point to the same list.

Now we want to copy the list referenced by a. We need to create a new list to attach b to it.
a and b reference different lists

b = a[:]
b = a.copy()

No comments:

Post a Comment