Reputation: 770
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?
Upvotes: 0
Views: 130
Reputation: 11338
Let's assume 'Reason' changes, so keep it in a variable removal. The code below manipulates the existing list
l = [[1, 'Reason', [('reason',), ('other_reason',)]], [2, 'other', [('dep',), ('path',)]], [3, "foo", [('bar',), ('bar1',)]]]
removal = 'Reason'
for idx, nest_list in enumerate(l):
if nest_list[1] == removal:
del l[idx]
# to change element to first pos
l.insert(0, l[-1])
del l[-1]
Then iterate over the list, look if the item in position 1 in the sublist matches. If it does, delete it from the list.
Upvotes: 1
Reputation: 5027
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'
.
Upvotes: 2