Create range without certain numbers
Solution 1
You can use a list comprehension to filter the 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]
This filters out all numbers in y
from the range.
You can also turn it into a generator (which you could only iterate over once but which would be faster for (very) large n
) by replacing [
with (
and ]
with )
. Further, in Python 2, you can use xrange
instead of range
to avoid loading the entire range into memory at once. Also, especially if y
is a large list, you can turn it into a set
first to use O(1) membership checks instead of O(n) on list
or tuple
objects. Such a version might look like
s = set(y)
x = (i for i in range(n) if i not in s)
Solution 2
hlt's answer is ideal, but I'll quickly suggest another way using set
operations.
n = 10
y = [3, 7, 8]
x = set(range(n)) - set(y)
x
will be a set
object. If you definitely need x
to be a list
, you can just write x = list(x)
.
Note that the ordering of a set in Python is not guaranteed to be anything in particular. If order is needed, remember to sort.
Karnivaurus
Updated on June 17, 2022Comments
-
Karnivaurus almost 2 years
I want to create a range
x
from0 ... n
, without any of the numbers in the listy
. How can I do this?For example:
n = 10 y = [3, 7, 8] x = # Do Something
Should give the output:
x = [0, 1, 2, 4, 5, 6, 9]
One naive way would be to concatenate several ranges, each spanning a set of numbers which have been intersected by the numbers in
y
. However, I'm not sure of what the simplest syntax to do this is in Python.