Removing specific elements from a list in Python

Question:

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]
Asked By: user20032724

||

Answers:

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]
Answered By: bitflip
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.