3

I want to create an array of numbers from 1 to n without the number x,

is there a "prettier" way to do it instead of [i for i in range(n) if i != x]? thanks!

3 Answers3

0

I would suggest using itertools.chain :

for a in itertools.chain(range(x), range(x+1, n)):
    print(a)

or

list(itertools.chain(range(x), range(x+1, n)))

I don't know why, but [itertools.chain(range(x), range(x+1, n))] doesn't work though.

EDIT: Thanks to @rafaelc for how to make it work on square brackets.

[*itertools.chain(range(x), range(x+1, n))]
bracco23
  • 2,181
  • 10
  • 28
0

You can concatenate two ranges:

np.concatenate((np.arange(x), np.arange(x + 1, n)))

You can also delete an item:

np.delete(np.arange(n), x)

You can mask:

mask = np.ones(n, dtype=bool)
mask[x] = False
np.arange(n)[mask]

You can even use a masked array, depending on your application:

a = np.ma.array(np.arange(n), mask=np.zeross(n, dtypebool))
a.mask[x] = True=
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

Using advanced indexing with np.r_.

np.arange(n)[np.r_[0:x, x+1:n]]

def myrange(n, exclude):
    return np.arange(n)[np.r_[0:exclude, exclude+1:n]]

>>> myrange(10, exclude=3)
array([0, 1, 2, 4, 5, 6, 7, 8, 9])

Timings

%timeit myrange(10000000, 7008)
1 loop, best of 3: 79.1 ms per loop

%timeit other(10000000, 7008)
1 loop, best of 3: 952 ms per loop

where

def myrange(n, exclude):
    return np.arange(n)[np.r_[0:exclude, exclude+1:n]]

def other(n, exclude):
    return [i for i in range(n) if i != x]
rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • Preferably, if I am creating a function for it, shouldn't I just use `[i for i in range(n) if i != x]` as it is easier to read? is there any advantage for advanced indexing in this case? –  Dec 17 '19 at 14:56
  • 1
    @Tomergt45 Sure is easier to read, but way slower. The function name `myrange` and some docstrings should make this readable, and you'd still benefit from the fast speed. I've added some timings to illustrate. Another detail is that a list comprehension yields a python list, while `np.arange` +`np.r_` gives a numpy array directly – rafaelc Dec 17 '19 at 14:58