Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting elements in a given list only?

Tags:

python

list

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.

like image 716
Feryll Avatar asked Feb 17 '23 10:02

Feryll


2 Answers

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

like image 60
Jan Vorcak Avatar answered Feb 28 '23 04:02

Jan Vorcak


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.

like image 21
Henry Keiter Avatar answered Feb 28 '23 03:02

Henry Keiter