Removing only items in a given list?

New to this: what's the best way to copy (numeric) items from one list to another without binding items in both lists? For instance:

A=[[6,2,-1],[9,-2,3]] B=A[0] del B[0] 

will also set A to [[2,-1],[9,-2,3]] , although I would like A stay the same.

+4
source share
3 answers

The problem is that by doing this

 B=A[0] 

You just make another link to list A

You probably want to make a copy of the list, for example

 B=list(A[0]) 

In case the list contains an object that also needs to be copied, you need to completely copy the entire list

 import copy B = copy.deepcopy(A[0]) 

but you do not need it for integers

+3
source

Your code makes B just a reference to the first element in A This is a problem because the first element in A is a mutable object, namely a list. You want to copy elements A[0] to a new list, which you will name B :

 b = a[0][:] # lowercase variable names according to PEP8 

Note that this still makes small copies of the elements in A[0] . This will work for your case, since you said that these elements are numeric, which means they are immutable. If, however, you had more nested lists contained in A[0] , or other mutable objects instead of numbers, you might run into the same problem later, at the same level below. Just be careful to pay attention to where you need whole new objects and where there are enough links.

+3
source

Initialize B as a list and use .append() instead of =

 A=[[6,2,-1],[9,-2,3]] B = [] B.append(A[0]) 

See post for more details, but the bottom line is that using = duplicates a pointer to a list in memory. While using append ensures that the data contained in the duplicate list is instead of the list pointer itself.

+2
source

Source: https://habr.com/ru/post/1482457/


All Articles