Create a range without specific numbers
I want to create a range x
from 0 ... n
, without any numbers in the list y
. How can i do this?
For example:
n = 10
y = [3, 7, 8]
x = # Do Something
Should produce the result:
x = [0, 1, 2, 4, 5, 6, 9]
One naive way would be to combine multiple ranges, each spanning a set of numbers that were crossed by the numbers in y
. However, I'm not sure if the simplest syntax to do this is in Python.
source to share
You can use a list comprehension to filter a range from 0
to n
: range(n)
generates a list (or in Python 3, a generator object) from 0
to n - 1
(including both ends):
x = [i for i in range(n) if i not in y]
Selects all numbers y
from a range.
You can also turn it into a generator (which you could sort through just once, but that would be faster for a (very) large n
), replacing [
on (
and ]
on )
, in addition, in Python 2, you can use xrange
instead range
, to not immediately download the entire range into memory. Also, especially if it y
is a large list, you can first turn it into set
to use O (1) membership checks instead of O (n) on objects list
or tuple
. Such a version might look like
s = set(y)
x = (i for i in range(n) if i not in s)
source to share
Hlt's answer is perfect, but I'll quickly suggest another way using operations set
.
n = 10
y = [3, 7, 8]
x = set(range(n)) - set(y)
x
will be an object set
. If you definitely need x
how list
, you can just write x = list(x)
.
Note that set ordering in Python is not guaranteed to be anything special. If an order is required, do not forget to sort.
source to share