Changing the first list changes another list too

I have a list of the form

a = [[1,2][3,4][5,6][7,8]]

Somewhere in the code I do

b=a[:]
b[0][0]=9

and this changes both b and a :

>>> print a
[[9,2][3,4][5,6][7,8]]
>>> print b
[[9,2][3,4][5,6][7,8]]

I tried using b=a[:]

Why does b change at all?

1 Like

It is because when you assign b = a in python, it is copied by reference. Now b is like an alias for a. If you want to copy by value, do b = list(a).

4 Likes

It only makes a shallow copy of the list and same as b = a[:].
To also copy the inner lists (and any other types recursively) you need deepcopy.

import copy
b = copy.deepcopy(a)
4 Likes

In python, when you do b = a or b = a[:] ( basically the same thing ) it copies the array by reference meaning when you make changes to one the other one automatically gets changed cause the are the same just being called with two different names
If you want to just copy the elements you should use copy function ( predefined ) . + you can also use what is suggested by @aneee004 -> b = list(a) .

1 Like

I have tried this too , still same

This is working , thnx

This doesn’t work.

2 Likes

LMAO , fk python. :rofl: :rofl: @aneee004

2 Likes

I am never coding in python :mask:.

1 Like

Use Copy module. Follow this link.