New at this: What's the best way to copy (numerical) elements from one list to another without binding the elements across both lists? Eg:
A=[[6,2,-1],[9,-2,3]]
B=A[0]
del B[0]
will also set A
to [[2,-1],[9,-2,3]]
, even though I'd like A
to remain unchanged.
The problem is that by doing this
B=A[0]
You just make another reference to the A list
You probably want to make a copy of the list like
B=list(A[0])
In case list contains object that needs to be copied as well, you'll need to deep copy the whole list
import copy
B = copy.deepcopy(A[0])
but you don't need this for integers
Your code is making B
simply a reference to the first item in A
. This is a problem because the first item in A
is a mutable object, namely a list. What you want to do is copy the elements of A[0]
into a new list, which you will call B
:
b = a[0][:] # lowercase variable names according to PEP8
Note that this still only makes shallow copies of the items in a[0]
. This will work for your case since you've said that those elements are numeric, which means they're immutable. If, however, you had more nested lists contained in a[0]
, or other mutable objects instead of numbers, you could end up with the same problem later on, one level further down. Just be careful to pay attention to where you need whole new objects, and where references are sufficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With