pietà pietà - 3 years ago 250
Python Question

How to delete a list element from a list in python?

I have a list of lists like this one :

[[1, 'Reason', [('reason',), ('other_reason',)]], [2, 'other', [('dep',),
('path',)]], [3, "foo", [('bar',), ('bar1',)]] ]


I have this list in a function that sometimes return it as it is (an edit mode) and in (show details) mode change the last element from the last position to the first position , so the list will be like :

[ [1, "foo", [('bar',), ('bar1',)]], [2, 'other', [('dep',), ('path',)]],
[3, 'Reason', [('reason',), ('other_reason',)]]]


I want to remove the list that contains 'Reason' (the first list in the first example ).

I tried using
list.index('Reason')
method to have index but it is not working since 'Reason' is not an element of the list.

also the index is not the same so
del list[0]
is not a good choice

Any ideas?

Answer Source

This?

>>> l = [[1, 'Reason', [('reason',), ('other_reason',)]], [2, 'other', [('dep',), ('path',)]], [3, "foo", [('bar',), ('bar1',)]] ]>>>
>>> [e for e in l if 'Reason' not in e]
[[2, 'other', [('dep',), ('path',)]], [3, 'foo', [('bar',), ('bar1',)]]]
>>>

Explanation: this builds a new list from the first one, putting in it all elements except the ones containing 'Reason'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download