We have the following list as input:
[[-5, -1], [1, -5], [5, -1]]
I have created a function which takes clist as a list and number a random number that I want to remove from the list.
The function should remove all the nested lists that contain the given number and remove the negative number within the nested list
def reduce(self, clist, number):
self.temp = list(clist)
# remove the nested list that contain the given number
for item in clist:
if number in item:
self.temp.remove(item)
# remove the negative number within the nested list
for obj in self.temp:
try:
obj.remove(-number)
except:
pass
return self.temp
Let's pick 1 as a number and run the code.
The first
forloop will remove all nested lists that contain the given number and will get the following:self.temp = [[-5, -1], [5, -1]]clist = [[-5, -1], [1, -5], [5, -1]]The second
forloop should remove all negativenumberwithin the nested lists but we get the following:self.temp = [[-5], [5]]clist = [[-5], [1, -5], [5]]
What I do not get is why clist gets affected when I am working on the second for loop, especially when I'm working on self.temp list? It should be without reference to the original list, but I am missing something out. Help?