0

my problem is that when I create a list,'a' and copy its content in another list c by using

c=a[:]

now when I call a function to numerically sort 'a', I get it sorted but the values of 'c' also gets converted even though I made no change in 'c' please refer to the picture for input and outputs! Thanks in advance

enter image description here

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94

5 Answers5

2

This is because c = a[:] copies the top level list, but the items inside it are references to the same sublists. If you want to avoid this behavior, you can do a deep copy:

from copy import deepcopy
c = deepcopy(a)
Amber
  • 507,862
  • 82
  • 626
  • 550
0

Odd, it should not be changed:

>>> a=[1,4,5,7,22,41,4,-5,66,22,12]
>>> c=a[:]
>>> a.sort()
>>> a
[-5, 1, 4, 4, 5, 7, 12, 22, 22, 41, 66]
>>> c
[1, 4, 5, 7, 22, 41, 4, -5, 66, 22, 12]

You can try to do this with c = list(a) as well. In both cases you copy the array by value and not by reference.

You should know though, that these two methods have limitations with collections of mutable objects as inner objects keep their references intact. So if you want a full copy you can use copy.deepcopy and use it like this:

>>> from copy import deepcopy
>>> a = [[1,2],[3],[4]]
>>> c = deepcopy(a)
Megabeets
  • 1,378
  • 11
  • 19
0

The problem is this line: d[i][j] = int(d[i][j]). This modifies a, because d has not been copied. This also modifies c because only the list has been copied, not the elements of the list, so modifying them modifies both lists. To fix this, you could, as the other answer states, deepcopy it, or just use c = [element[:] for element in a].

internet_user
  • 3,149
  • 1
  • 20
  • 29
0

There's a more comprehensive answer at How to clone or copy a list?

The simple answer is: if you have objects in your list - you need to deep copy the list, i.e. copy the objects as well...

0

The issue is actually with this line:

d[i][j] = int(d[i][j])

This is modifying your input (a).

To fix this, you could try modifying your function to copy the input and modify it directly:

b = d[:]
...
b[i][j] = int(b[i][j])

Then you don’t need to reassign b.

dantiston
  • 5,161
  • 2
  • 26
  • 30