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

$
0
0

A very simple approach independent of python version was missing in already given answers which you can use most of the time (at least I do):

new_list = my_list * 1       #Solution 1 when you are not using nested lists

However, If my_list contains other containers (for eg. nested lists) you must use deepcopy as others suggested in the answers above from the copy library. For example:

import copynew_list = copy.deepcopy(my_list)   #Solution 2 when you are using nested lists

.Bonus: If you don't want to copy elements use (aka shallow copy):

new_list = my_list[:]

Let's understand difference between Solution#1 and Solution #2

>>> a = range(5)>>> b = a*1>>> a,b([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])>>> a[2] = 55 >>> a,b([0, 1, 55, 3, 4], [0, 1, 2, 3, 4])

As you can see Solution #1 worked perfectly when we were not using the nested lists. Let's check what will happen when we apply solution #1 to nested lists.

>>> from copy import deepcopy>>> a = [range(i,i+4) for i in range(3)]>>> a[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]>>> b = a*1>>> c = deepcopy(a)>>> for i in (a, b, c): print i   [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]][[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]][[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]>>> a[2].append('99')>>> for i in (a, b, c): print i   [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5, 99]][[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5, 99]]   #Solution#1 didn't work in nested list[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]       #Solution #2 - DeepCopy worked in nested 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>