0

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)?

2 Answers 2

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

1

you can also use:

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

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.