291

In Python, how do I create a numpy array of arbitrary shape filled with all True or all False?

Michael Currie
  • 13,721
  • 9
  • 42
  • 58

7 Answers7

410

The answer:

numpy.full((2, 2), True)

Explanation:

numpy creates arrays of all ones or all zeros very easily:

e.g. numpy.ones((2, 2)) or numpy.zeros((2, 2))

Since True and False are represented in Python as 1 and 0, respectively, we have only to specify this array should be boolean using the optional dtype parameter and we are done:

numpy.ones((2, 2), dtype=bool)

returns:

array([[ True,  True],
       [ True,  True]], dtype=bool)

UPDATE: 30 October 2013

Since numpy version 1.8, we can use full to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):

numpy.full((2, 2), True, dtype=bool)

UPDATE: 16 January 2017

Since at least numpy version 1.12, full automatically casts to the dtype of the second parameter, so we can just write:

numpy.full((2, 2), True)
Michael Currie
  • 13,721
  • 9
  • 42
  • 58
  • 1
    dtype=int initialized array cannot be used for array element selection. – Jichao May 14 '16 at 02:07
  • 1
    This works. However, be careful because as @Jichao says, `a=np.ones((2,2))` followed by `a.dtype=bool` does NOT work. – medley56 Mar 12 '17 at 18:03
  • answer assumes that np.ones or np.zeros with dtype bool have to cast int array as boolean. Is this assumption true? I think it creates boolean array and doesn't create int array first and then cast. Kindly correct this answer if I am right – Alok Nayak Aug 24 '18 at 07:01
108
numpy.full((2,2), True, dtype=bool)
fmonegaglia
  • 2,749
  • 2
  • 24
  • 34
  • 13
    +1 I think this should be the accepted answer. It seems more natural to fill an array with bools, than to fill it with numbers to cast them to bools. – Zelphir Kaltstahl Apr 18 '16 at 20:55
  • 6
    The `ones` and `zeros` answers do not construct an array of integers. They build an array of bools directly. – user2357112 Jun 29 '16 at 16:01
  • 1
    Is `numpy.full((2,2), True)` an equivalent? – Pavel Oct 15 '17 at 16:34
  • It is in numpy 1.12+. I dont remember whether it applies to former versions either – fmonegaglia Oct 20 '17 at 12:15
  • Surly dtype is stored separately from the data itself when possible? I can't imagine numpy doing any heavy lifting to convert `int 1` to `bool True`. – BallpointBen May 08 '18 at 19:02
  • @BallpointBen: dtype and data are separate, but data representation is dependent on the dtype. Converting an array of integers to an array of booleans requires creating an entirely new array with an entirely new data buffer and performing elementwise conversion. (None of the existing answers do an int array to bool array conversion, though.) – user2357112 Jan 13 '21 at 20:46
  • 1
    full tends to be much slower than ones or zeros – MrE Mar 11 '21 at 17:26
33

ones and zeros, which create arrays full of ones and zeros respectively, take an optional dtype parameter:

>>> numpy.ones((2, 2), dtype=bool)
array([[ True,  True],
       [ True,  True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
       [False, False]], dtype=bool)
user2357112
  • 260,549
  • 28
  • 431
  • 505
9

If it doesn't have to be writeable you can create such an array with np.broadcast_to:

>>> import numpy as np
>>> np.broadcast_to(True, (2, 5))
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

If you need it writable you can also create an empty array and fill it yourself:

>>> arr = np.empty((2, 5), dtype=bool)
>>> arr.fill(1)
>>> arr
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

These approaches are only alternative suggestions. In general you should stick with np.full, np.zeros or np.ones like the other answers suggest.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
7

benchmark for Michael Currie's answer

import perfplot

bench_x = perfplot.bench(
    n_range= range(1, 200),
    setup  = lambda n: (n, n),
    kernels= [
        lambda shape: np.ones(shape, dtype= bool),
        lambda shape: np.full(shape, True)
    ],
    labels = ['ones', 'full']
)

bench_x.show()

enter image description here

hammi
  • 804
  • 5
  • 14
  • 1
    Glad to see that `full` has only a fixed time penalty, and not a time penalty that scales with the size of the array. So the larger the array, the less important this difference becomes. – Michael Currie Feb 14 '23 at 16:32
5

Quickly ran a timeit to see, if there are any differences between the np.full and np.ones version.

Answer: No

import timeit

n_array, n_test = 1000, 10000
setup = f"import numpy as np; n = {n_array};"

print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")

Result:

np.ones: 0.38416870904620737s
np.full: 0.38430388597771525s


IMPORTANT

Regarding the post about np.empty (and I cannot comment, as my reputation is too low):

DON'T DO THAT. DON'T USE np.empty to initialize an all-True array

As the array is empty, the memory is not written and there is no guarantee, what your values will be, e.g.

>>> print(np.empty((4,4), dtype=bool))
[[ True  True  True  True]
 [ True  True  True  True]
 [ True  True  True  True]
 [ True  True False False]]
Joschua
  • 324
  • 3
  • 8
-1
>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True]], dtype=bool)

numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html

nikithashr
  • 45
  • 4
  • 6
    Well, [another answer](http://stackoverflow.com/a/35224478/5393381) already answered using `np.full` - more than one year ago! – MSeifert Apr 15 '17 at 02:41