-6

As a hypothetical example:

>>> a = [1, 2, 3]
>>> b = a
>>> b[0] = 4
>>> b
[4, 2, 3]
>>> a
[4, 2, 3]

I know that this occurs because the references to both a and b are identical, and therefore point to the same bytes of memory. A change in the bytes referenced by b will be reflected in a, since they share the same memory.

What is the best way to work around this, so that a remains the original value, and after b is made from a, changes to b will not go to a, also.

Specific code:

outputs = []
a = [[0,2,5],[4,2,0],[6,0,0]]
for i in range(3):
  for j in range(3):
    if not a[i][j]:
      b = a
      b[i][j] = 1
      outputs.append(b)

This returns:

outputs = [[[1,2,5],[4,2,1],[6,1,1]],
           [[1,2,5],[4,2,1],[6,1,1]],
           [[1,2,5],[4,2,1],[6,1,1]]]
bcdan
  • 1,438
  • 1
  • 12
  • 25

2 Answers2

1

You can copy the original list by slicing it:

a = [1, 2, 3]
b = a[:]

Or using the built in list list() funtion:

b = list(a)

You could also use list comprehension in place of your nested for loops:

b = [[i if i else 1 for i in j] for j in a]
user3636636
  • 2,409
  • 2
  • 16
  • 31
0

This :

new_list = list(old_list)

And so this will happen -

>>> a = [1,2,3]
>>> b = list(a)
>>> b.append(8)
>>> b
[1, 2, 3, 8]
>>> a
[1, 2, 3]
Utsav T
  • 1,515
  • 2
  • 24
  • 42