Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove an element from a nested list?

Tags:

python

if I have a nested list such as:

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

if I write m.remove(345) it gives an error message saying the element is not in the list.

I want to know how to remove an element from the nested list, easily.

like image 997
kaki Avatar asked Jun 16 '10 16:06

kaki


2 Answers

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) only removes the first occurrance of of 345 (if it exists). The above code removes all occurrances of 345.

like image 74
unutbu Avatar answered Nov 07 '22 23:11

unutbu


There is no shortcut for this. You have to remove the value from every nested list in the container list:

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

If you want similiar 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")
like image 28
Ferdinand Beyer Avatar answered Nov 07 '22 23:11

Ferdinand Beyer