Normally assignment with = does not make a copy of the list. In fact assignment makes two variables to point to same location in mamory.
---------------------------------------------------
so to copy the list you have different options :
you can slice it :
use generic copy.copy:
use built in function list():
OR if the list contains object use generic copy.deepcopy()
Obviously the slowest and most memory-needing method, but sometimes unavoidable.
!!!! NOTE :
But be aware that copy.copy(), list[:] and list(list), unlike copy.deepcopy() and the python version don't copy any lists, dictionaries and class instances in the list, so if the originals change, they will change in the copied list too and vice versa.
colors = ['red', 'blue', 'green'] print colors[0] ## red print colors[2] ## green print len(colors) ## 3
b = colors ## Does not copy the list
---------------------------------------------------
so to copy the list you have different options :
you can slice it :
new_list = old_list[:]
ORuse generic copy.copy:
import copy
new_list = copy.copy(old_list)
ORuse built in function list():
new_list = list(old_list)
OR if the list contains object use generic copy.deepcopy()
import copy
new_list = copy.deepcopy(old_list)
Obviously the slowest and most memory-needing method, but sometimes unavoidable.
!!!! NOTE :
But be aware that copy.copy(), list[:] and list(list), unlike copy.deepcopy() and the python version don't copy any lists, dictionaries and class instances in the list, so if the originals change, they will change in the copied list too and vice versa.
No comments:
Post a Comment