Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am working on the list. I wanted to remove the list if it consists of the value -1 in it. I have to use the below code which was giving me the proper results as I wanted. I don't know what happened now the Jupyter is not showing me the results. Can anyone suggest me the solution for it?

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 feel whenever I am removing the region from the list named regions the counter of the regions in the nested list is been modified and this is giving me the error "running out of index value" before the iterating through the nested list.

I have doubt is this the proper approach or is there any other way to solve it?  Am I going in the correct way?

1 Answer

0 votes
by (36.8k points)

This is the simple way to comprehensive list as shown below:

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

The output is:

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

 If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

Browse Categories

...