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

$
0
0

Note that there are some cases where if you have defined your own custom class and you want to keep the attributes then you should use copy.copy() or copy.deepcopy() rather than the alternatives, for example in Python 3:

import copyclass MyList(list):    passlst = MyList([1,2,3])lst.name = 'custom list'd = {'original': lst,'slicecopy' : lst[:],'lstcopy' : lst.copy(),'copycopy': copy.copy(lst),'deepcopy': copy.deepcopy(lst)}for k,v in d.items():    print('lst: {}'.format(k), end=', ')    try:        name = v.name    except AttributeError:        name = 'NA'    print('name: {}'.format(name))

Outputs:

lst: original, name: custom listlst: slicecopy, name: NAlst: lstcopy, name: NAlst: copycopy, name: custom listlst: deepcopy, name: custom 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>