Search code examples
pythonlistnumpyrange

how to exclude `x` from `range(n)` using numpy


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!


Solution

  • 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]