How to remove an item from a nested list?

if I have a nested list, for example:

m=[[34,345,232],[23,343,342]] 

if I write m.remove(345) , it gives an error message indicating an item is not in the list.

I want to know how to remove an item from a nested list, easily

+4
source share
4 answers

There is no shortcut for this. You must remove the value from each nested list in the container list:

 for L in m: try: L.remove(345) except ValueError: pass 

If you need a similar behavior like list.remove , use something like the following:

 def remove_nested(L, x): for S in L: try: S.remove(x) except ValueError: pass else: break # Value was found and removed else: raise ValueError("remove_nested(L, x): x not in nested list") 
+4
source
 In [5]: m=[[34,345,232],[23,343,342]] In [7]: [[ subelt for subelt in elt if subelt != 345 ] for elt in m] Out[7]: [[34, 232], [23, 343, 342]] 

Note that remove(345) removes only the first of 345 (if it exists). The above code deletes all 345 entries.

+2
source
 i=0 for item in nodes: for itm in item: m=database_index[itm] print m if m[1]=='text0526' or m[1]=='text0194' or m[1]=='phone0526' or m[1]=='phone0194': nodes[i].remove(itm) i+=1 

it's me, as I solved my problem, using the i variable to save the above level of the nested list.

+1
source

If you have more than one nested level, this can help.

 def nested_remove(L, x): if x in L: L.remove(x) else: for element in L: if type(element) is list: nested_remove(element, x) >>> m=[[34,345,232],[23,343,342]] >>> nested_remove(m, 345) >>> m [[34, 232], [23, 343, 342]] >>> m=[[34,[345,56,78],232],[23,343,342]] >>> nested_remove(m, 345) >>> m [[34, [56, 78], 232], [23, 343, 342]] 
+1
source

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


All Articles