list2 = list1
problem:
both list1 & list2 take reference to the same piece of memory, modification on any of them will take effect on another one. (actually not copying)
1. list slicing
list2 = list1[:]
adv:
fastest under most cases
supported both in python 2 and 3
disad:
syntax slightly weird. May not be intuitive to other developers.
can’t copy objects, arrays, etc in the original array (i.e. only applicable to 1D arrays)
2. list.copy (built-in list function in python 3) [recommended]
list2 = list1.copy
adv:
only slightly slower than list slicing mentioned above
intuitive, simple
disad:
not supported in python 2
can’t copy objects, arrays, etc in the original array (i.e. only applicable to 1D arrays)
3. list(…) (built-in list function)
list2 = list(list1)
adv:
slightly slower than list.copy mentioned above
supported both in python 2 and 3
intuitive, simple
disad:
can’t copy objects, arrays, etc in the original array (i.e. only applicable to 1D arrays)
4. copy.copy (copy package) [not recommended]
import copy
list2 = copy.copy(list1)
adv:
supported both in python 2 and 3
disad:
require import package
slower than the methods mentioned above
can’t copy objects, arrays, etc in the original array (i.e. only applicable to 1D arrays)
4. copy.deepcopy (copy package) [recommended when dealing with multidimensional array]
import copy
list2 = copy.deepcopy(list1)
adv:
can copy objects, arrays, etc in the original array (i.e. applicable to multidimensional arrays)
(briefly explain: instead of copying the referencing memory address only, deepcopy create a new instance pointing to a new memory address holding the same content for each object.)
disad:
require import package
deepcopy may cost more memory as new instances are created
much slower than the methods mentioned above
more:
when copying an array holding multiple identical objects
e.g. list1 = [a,a] where both a objects are pointing to the same memory
if we do list2 = copy.deepcopy(list1)
content of list2 = [a’, a’] instead of [a’, a’’] where both a’ objects are again pointing to the same memory
that’s mean deepcopy will also keep the same structure as the original list.