l00kitsjake
l00kitsjake

Reputation: 1015

Python - x not in list error

I have a list inside a list and I am trying to remove any values in side the nested list that are equal to -1. I am getting a "ValueError: list.remove(x): x not in list" error when I try to run my code, any idea what I am doing wrong?

for x in list:
    for i in x:
        if i == -1:
            list.remove(x)

Upvotes: 0

Views: 370

Answers (1)

arshajii
arshajii

Reputation: 129477

You shouldn't mutate a list while iterating over it. You also shouldn't name a variable list, since that name is used by a built-in function. You can achieve what you want via a simple list comprehension:

my_list = [[x for x in v if x != -1] for v in my_list]

Upvotes: 3

Related Questions