Reputation: 3
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
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
Reputation: 1486
You can use the following to copy a list to another list.
b = a.copy()
Upvotes: 0