Evan Kim
Evan Kim

Reputation: 829

Remove nested lists from a list if nested list contains a certain value

I have a nested list and I would like to remove the empty list [] and any nested list that has a value of -1 in it. Here is what I have so far, it was working earlier but I think jupyter was being buggy.

regions = [[], [2, -1, 1], [4, -1, 1, 3], [5, 0, -1, 4], [9, 10, 7, 8], 
                    [7, 6, 10], [8, 0, 5, 6, 7], [9, 2, 1, 3, 10], 
                    [9, 2, -1, 0, 8], [10, 3, 4, 5, 6]]

counter = range(len(regions))
for region in counter:
    print(region)
    for i in range(len(regions[region])): # IndexError: list index out of range
    #print(regions[region])
        if regions[region][i] == -1:
            regions.remove(regions[region])
            break
print(regions)

I think the issue is when I am removing a region from the regions list, the counter for the regions nested list is modified and that makes me run out of index values before I finish iterating through each nested list.

Also does my approach even make sense or is there a more native solution that I am overlooking (such as some sort of list comprehension, lambda, filter, etc)?

Upvotes: 0

Views: 763

Answers (2)

Reiner Czerwinski
Reiner Czerwinski

Reputation: 296

you can also use:

regions = list(filter(lambda r: r and (r.count(-1)==0),regions))

Upvotes: 1

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6920

You can simply use this list comprehension :

regions = [i for i in regions if i and (-1 not in i)]

Output :

[[9, 10, 7, 8], [7, 6, 10], [8, 0, 5, 6, 7], [9, 2, 1, 3, 10], [10, 3, 4, 5, 6]]

Upvotes: 2

Related Questions