title: How to pack arbitrary bit sequence in Python?
body: <p>I want to encode/compress some binary image data as a sequence if bits.  (This sequence will, in general, have a length that does not fit neatly in a whole number of standard integer types.)</p>
  
  <p>How can I do this without wasting space?  (I realize that, unless the sequence of bits has a "nice" length, there will always have to be a small amount [&lt; 1 byte] of leftover space at the very end.)</p>
  
  <p>FWIW, I estimate that, at most, 3 bits will be needed per symbol that I want to encode.  Does Python have any built-in tools for this kind of work?</p>