0

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.

1
  • b = list(a) will create a copy of list a. Also, in python these are referred to as list, not arrays. Commented Apr 2, 2020 at 15:46

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply do it with :

b = a[:]

Comments

0

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

b = a.copy()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.