Initialize array from another array

Rektek :

how can I do this the correct way?

a = ['1','2']
b = []
for value in a:
    b.append(value)

I need to do this because I want to change values in a but I want to keep them in b. When I do b = a it seems to just set pointers to the values in a.

Green Cloak Guy :

Duplicate reference (pointing to the same list):

b = a

Soft copy (all the same elements, but a different list):

b = a[:]      # special version of the slice notation that produces a softcopy
b = list(a)   # the list() constructor takes an iterable. It can create a new list from an existing list
b = a.copy()  # the built-in collections classes have this method that produces a soft copy

For a deep copy (copies of all elements, rather than just the same elements) you'd want to invoke the built-in copy module.:

from copy import deepcopy

b = deepcopy(a)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390863&siteId=1