user1452759
user1452759

Reputation: 9430

Remove a sub list from nested list based on an element in Python

I have the following list:

 l = [["a", "done"], ["c", "not done"]]

If the second element of each sub list is "done" I want to remove that the sub list. So the output should be:

l = [["c", "not done"]]

Obviously the below doesn't work:

for i in range(len(l)):
    if l[i][1] == "done":
        l.pop(0)

Upvotes: 2

Views: 11402

Answers (5)

Kenly
Kenly

Reputation: 26678

Use list comprehension:

l = [ item for item in l if item[-1] != 'done']

Upvotes: 0

Omer Demircan
Omer Demircan

Reputation: 16

status index is 1, you checked index 0

for i in range(len(l)):
       if(l[i][1] == "done"):
           l.pop(i)

Upvotes: 0

gipsy
gipsy

Reputation: 3859

Apply a filter for your criteria:

l = [["a", "done"], ["c", "not done"]]
l = filter(lambda x: len(x)>=2 and x[1]!='done', l)

Upvotes: 0

vks
vks

Reputation: 67968

l = [["a", "done"], ["c", "not done"]]
print [i for i in l if i[1]!="done"]

or use filter

l = [["a", "done"], ["c", "not done"]]
print filter(lambda x:x[1]!="done",l)

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

Use list_comprehension. It just builts a new list by iterating over the sublists where the second element in each sublist won't contain the string done

>>> l = [["a", "done"], ["c", "not done"]]
>>> [subl for subl in l if subl[1] != 'done']
[['c', 'not done']]
>>> 

Upvotes: 6

Related Questions