What is a fast and pythonic way to create a list from [1, ..., n]
that contains none of the numbers [i_1, ..., i_r]
. For example, running this function on [1, 2, 3, 4]
and [2,3]
should return [1, 4]
.
I am currently using a for loop to test "if i
is in [1, ..., n]
, then exclude it from the output array, else include it".
Is there a better and more pythonic way?
CodePudding user response:
As a pythonic way you can go with :
n = 5
l = [k for k in range(1,n) if not k in [2,3] ]
Not sure about speed though.
CodePudding user response:
A pythonic and fast way to do it:
l = [k for k in range(1,n 1) if k < i_1 or k > i_r]
Note that this is O(n), while @Adrien Mau's answer is O(n²).