title: How do I pack bits from one byte array to another efficiently in python3?
body: <p>I have a fairly large byte array in python. In the simplest situation the byte array only contains 0 or 1 values (0x00, 0x01), also the array is always a multiple of 8 in length. How can I pack these "bits" into another byte array (it doesn't need to be mutable) so the source index zero goes to the MSB of the first output byte etc.</p>
  
  <p>For example if <code>src = bytearray([1,0,0,0,1,0,0,1, 1,1,1,0,0,0,1,0, 1,1,1,1,1,1,1,1])</code>
  Desired output would be <code>b'\x89\xe2\xff'</code>.</p>
  
  <p>I could do it with a for loop and bit shifting and or-ing and concatenation, but there surely is a faster/better built-in way to do this.</p>
  
  <p>In a follow up question, I also might want to have the source byte array contain values from the set 0-3 and pack these 4 at a time into the output array. Is there a way of doing that?</p>
  
  <p>In general is there a way of interpreting elements of a list as true or false and packing them 8 at a time into a byte array?</p>