Search code examples
pythonnumpyzero

Exclude zero from np.linspace in one line


How can I remove zero from linspace?

this is my list:

np.linspace(-3, 3, 1)
--> [-3, -2, -1, 0, 1, 2, 3] 

And I want to achieve this:

[x if x != 0 for x in np.linspace(-3, 3, 1)]
--> [-3, -2, -1, 1, 2, 3]

Solution

  • First, to get your expected result you would need np.linspace(-3, 3, 7) to get 7 numbers. Second, your if statement has to be behind the interation in your list comprehension. Working code would be:

    import numpy as np
    
    print([int(x) for x in np.linspace(-3, 3, 7) if x != 0])