1

I am trying to make a function that is given a nested list, and deletes all occurrences of elements in to_eliminate. I understand why I would have this problem if I did new_list = input_list, but im doing new_list = input_list[:]. I even checked their id's and they are definitely different. I don't want to modify my original list.

Both segments of code do not work. When I return both input_list and new_list, I get the same result. I don't understand why, since I copied the original list, and they are two different objects.

smci
  • 32,567
  • 20
  • 113
  • 146
rochimer
  • 87
  • 8

2 Answers2

2

Your fundamental problem is that input_list[:] only shallow copies; if it contains mutable contents itself (in this case, nested lists) it's sharing aliases to mutable data, and modifying it in the "copy" is still modifying the contents of the original data structure.

If you can't use the copy module, and you've got a known 2D arrangement of lists, just perform the deep copy yourself, changing:

new_list = input_list[:]

to:

new_list = [sublst[:] for sublst in input_list]

and making sure to return new_list rather than input_list. That list comprehension just manually makes shallow copies of the second layer of lists into a brand new list. You can extend it further to greater levels of nesting, but it gets progressively more ridiculous the deeper you go.

The real answer is to let Python do the work for you, with copy.deepcopy, making it:

new_list = copy.deepcopy(input_list)

which will work no matter how deeply nested your data structure gets.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

This should work, if you need it inline, let me know and i'll update the answer, i was unsure based on your question:

input_list = [[1,2,3,4,5,6,7,8,9,0],[3,5,7,9,0],[1,2,3,4,5]]
remove_list = [1,4,7,0]

def eliminate(input_list, remove_list):
  new_list=[]
  for item in input_list:
    new_list.append(list(set(item) - set(remove_list)))
  return new_list

new_list = eliminate(input_list, remove_list)

new_list
[[2, 3, 5, 6, 8, 9], [9, 3, 5], [2, 3, 5]]
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24