Reputation: 584
Suppose I have a list of lists.
L = [[1,2,3], ['a',2,True],[1,44,33,12.1,90,2]]
I want to be able to remove all instances of a specific element from each of the sublists in the list L.
So for instance I might want to remove the number 2 so this would produce
L = [[1,3], ['a',True],[1,44,33,12.1,90]]
I tried to use this function + code:
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
for i in L:
i = remove_values_from_list(i, '2')
However the output still gives L in its original form and doesn't remove the 2.
Upvotes: 0
Views: 195
Reputation: 198324
i
is a variable that is not connected to L
. It is assigned a value from L
, then you reassign it to something else; this will not affect L
at all.
A non-destructive way to do this (i.e. preserve L
, make a new list for the result):
newL = [[value for value in the_list if value != val] for the_list in L]
A destructive way (i.e. change L
itself):
for the_list in L:
while value in the_list:
the_list.remove(value)
Upvotes: 5
Reputation: 6920
Try this :
def remove_values_from_list(the_list, val):
return [[v for v in l1 if v!= val] for l1 in the_list]
In your code, you were checking whether only one sub-list is equivalent to the the val
parameter. You need to check it inside sub-lists. Also a secondary mistake would be to check items inside sub-lists with exact type. You are searching for '2'
(str type) where as there is 2
(int type) in the sub-lists.
Upvotes: 0