Rektek
Rektek

Reputation: 3

Initialize array from another array

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.

Upvotes: 0

Views: 1100

Answers (3)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

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)

Upvotes: 2

Nikhil Gupta
Nikhil Gupta

Reputation: 1486

You can use the following to copy a list to another list.

b = a.copy()

Upvotes: 0

Giuseppe
Giuseppe

Reputation: 678

You can simply do it with :

b = a[:]

Upvotes: 1

Related Questions