Home > OS >  Removing specific elements from a list in Python
Removing specific elements from a list in Python

Time:10-03

I have a list N. I want to remove elements mentioned in I from N. But there is an error. I present the expected output.

N=[i for i in range(1,11)]
I=[4,9]

N.remove(I)
print(N)

The error is

in <module>
    N.remove(I)

ValueError: list.remove(x): x not in list

The expected output is

[1,2,3,5,6,7,8,10]

CodePudding user response:

You are trying to remove a list which is not in N. You either have to call .remove() for every element in I or you can do it like this:

I = [4, 9]
N = [i for i in range(1, 11) if i not in I]  # [1, 2, 3, 5, 6, 7, 8, 10]
  • Related