How to copy a list that will not be changed when a function is called in Python

I worked on these functions (see this ):

def removeFromList(elementsToRemove): def closure(list): for element in elementsToRemove: if list[0] != element: return else: list.pop(0) return closure def func(listOfLists): result = [] for i, thisList in enumerate(listOfLists): result.append(thisList) map(removeFromList(thisList), listOfLists[i+1:]) return result 

I have a list that I want to pass as an argument, but I want this list to remain intact. I tried:

 my_list = [[1], [1, 2], [1, 2, 3]] print my_list #[[1], [1, 2], [1, 2, 3]] copy_my_list = list (my_list) #This also fails #copy_my_list = my_list [:] print id (my_list) == id (copy_my_list) #False print func (copy_my_list) #[[1], [2], [3]] print my_list #[[1], [2], [3]] 

But he is changing my initial list. Any ideas?

+4
source share
3 answers

Use copy.deepcopy :

 from copy import deepcopy new_list = deepcopy([[1], [1, 2], [1, 2, 3]]) 

Demo:

 >>> lis = [[1], [1, 2], [1, 2, 3]] >>> new_lis = lis[:] # creates a shallow copy >>> [id(x)==id(y) for x,y in zip(lis,new_lis)] [True, True, True] #inner lists are still the same object >>> new_lis1 = deepcopy(lis) # create a deep copy >>> [id(x)==id(y) for x,y in zip(lis,new_lis1)] [False, False, False] #inner lists are now different object 
+7
source

both with list(my_list) and my_list[:] you will get a shallow copy of the list.

 id(copy_my_list[0]) == id(my_list[0]) # True 

so use copy.deepcopy to avoid your problem:

 copy_my_list = copy.deepcopy(my_list) id(copy_my_list[0]) == id(my_list[0]) # False 
+3
source

Use a tuple. my_list = ([1], [1, 2], [1, 2, 3])

my_list now immutable, and anytime you want to use a mutable copy, you can just use list(my_list)

 >>> my_list = ([1], [1, 2], [1, 2, 3]) >>> def mutate(aList): aList.pop() return aList >>> mutate(list(my_list)) [[1], [1, 2]] >>> my_list ([1], [1, 2], [1, 2, 3]) >>> 

As someone caught my attention, this solution is not reliable. The tuple itself is not changed, but its elements (if they are mutable objects - which lists).

+1
source

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


All Articles