Fastest / most efficient random bit indexing in Python Using Python/Cython, I am trying to construct an efficient way to index boolean values. I have been trying to use the bitarray and/or bitstring packages to construct a fast, non memory intensive way to hold a lot of booleans. My goal was for a list like object that could be sliced as such, and actually managed the bool values in real bits of data:
&gt;&gt;&gt; from bitarray import bitarray
&gt;&gt;&gt; array = bitarray(1000000) # creates 1000000 allocated bits
&gt;&gt;&gt; array.setall(False)
&gt;&gt;&gt; array[4] # holds boolean values
False
&gt;&gt;&gt; from timeit import timeit
&gt;&gt;&gt; timeit(setup = 'from __main__ import array',
           stmt = 'array[500000]')
0.21002184844218164
# one million iterations, making each iteration 210 ns

&gt;&gt;&gt; from bitstring import BitArray
&gt;&gt;&gt; array = BitArray(1000000) # just as we did in the first example
&gt;&gt;&gt; array[6] # all are False by default
False
&gt;&gt;&gt; from timeit import timeit
&gt;&gt;&gt; timeit(setup = 'from __main__ import array',
           stmt = 'array[500000]')
2.6748261753875795
# oh no, this one is very slow, each iteration takes 2674 ns

As you can see, there are already packages that construct this binary data and allow you to index it at random. Would it be possible to get to an even lower level to the RAM myself? 210ns is fast, but I would like to get indexing below 40ns on a 1000000 bit array. How can this be done?
Edit:
Individual item assignment to the boolean array after it is created, would be nice, but it is not required.
What exactly do you want to do with your array of booleans? If you used numpy, you could instantiate your boolean array as an array of uint8 one eighth the size of the boolean array, e.g.

In [38]: a = np.random.randint(256, size=(1000000//8,)).astype(np.uint8)


To extract items, you could do something like:

In [39]: def get_bools(a, i):
   ....:     b = i // 8
   ....:     o = i % 8
   ....:     mask = 1 &lt;&lt; o
   ....:     return (a[b] &amp; mask) != 0
   ....:


If you run this to extract a single item, the speed is appalling:

In [40]: idx = 500000

In [41]: %timeit get_bools(a, idx)
100000 loops, best of 3: 4.53 us per loop


But if you do it for 1000 items at once, things look (much) better:

In [42]: idx = np.random.randint(1000000, size=(1000,))

In [43]: %timeit get_bools(a, idx)
10000 loops, best of 3: 31.1 us per loop


Note that the last timing means ~30 ns per item retrieved, right where you wanted to be.

If you need to extract the boolean values one at a time, you are going to have to deal with the painful Python overhead. Notice that simply getting a single item from an array is terribly slow:

In [44]: %timeit a[62500]
10000000 loops, best of 3: 135 ns per loop


But if you can vectorize your code with numpy, or use a C array directly from cython, then you should have no problem in achieving your speed goal.