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.
3 Answers 3
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)
answered Apr 2, 2020 at 15:24
Green Cloak Guy
24.8k4 gold badges39 silver badges58 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can simply do it with :
b = a[:]
answered Apr 2, 2020 at 15:21
Giuseppe
6681 gold badge6 silver badges16 bronze badges
Comments
You can use the following to copy a list to another list.
b = a.copy()
answered Apr 2, 2020 at 15:23
Nikhil Gupta
1,4961 gold badge14 silver badges19 bronze badges
Comments
lang-py
b = list(a)will create a copy of list a. Also, inpythonthese are referred to as list, not arrays.