0

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?

3 Answers 3

2

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'.

Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't replace the last element into the first, plus it creates a new list instead of modifying the existing list.
From the question, I only understand the reversion as already been done. I add the relevant part then.
@Vinny actually changing the order does not seem to be part of the question. As far as I understand, it was only there to tell the elements' order may change, that's all.
Thanks a lot :) yup, changing the order is not a part of the question
1
[l for l in list if not "Reason" in l]

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.