pietà
pietà

Reputation: 770

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?

Upvotes: 0

Views: 130

Answers (3)

Chen A.
Chen A.

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

Baptiste
Baptiste

Reputation: 25

[l for l in list if not "Reason" in l]

Upvotes: 1

zezollo
zezollo

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

Related Questions