Bitarray
The bitarray library (current version 3.8.0) provides an efficient object type for representing arrays of booleans, implemented as a C extension for high performance. Bitarrays behave much like standard Python lists, supporting sequence operations like slicing and concatenation, as well as bitwise operations. It allows users to choose between little-endian and big-endian representations, with eight bits packed into one byte in a contiguous memory block. The library maintains an active release cadence, with frequent updates addressing features and bug fixes.
Warnings
- breaking Python 2.7 support was removed in `bitarray` 3.0.0 (October 2024). Python 3.5 support was dropped in `bitarray` 3.4.0 (May 2025). Ensure your project uses Python 3.6 or newer.
- breaking In `bitarray` 3.0.0, the `.decode()` and `.search()` methods now return iterators, replacing the previously dedicated `.iterdecode()` and `.itersearch()` methods, which were removed. Additionally, `util.rindex()` was removed, favoring `.index(..., right=1)`, and `util.make_endian()` was removed, replaced by `bitarray(..., endian=...)`.
- breaking As of `bitarray` 3.4.0, the `.endian()` *method* was removed and replaced by a `.endian` *data descriptor* (property). Attempting to call `.endian()` will result in an error.
- gotcha Shift operations (`<<`, `>>`) on `bitarray` objects have specific, defined behavior, which may differ from expectations based on C or general Python integer shifts. The length of the bitarray is never changed; blanks are filled with 0s. Negative shifts raise `ValueError`. Shifts larger than or equal to the bitarray's length result in an all-zero bitarray.
Install
-
pip install bitarray
Imports
- bitarray
from bitarray import bitarray
- util
from bitarray import util
Quickstart
from bitarray import bitarray
# Create an empty bitarray of length 10, initialized to zeros
a = bitarray(10)
print(f"Initial bitarray: {a} (length: {len(a)})")
# Set individual bits
a[0] = 1
a[3] = 1
print(f"After setting bits: {a}")
# Append bits
a.append(0)
a.extend('101') # Extend with a string of '0's and '1's
print(f"After appending and extending: {a} (length: {len(a)})")
# Initialize from a string or list
b = bitarray('1101_0010') # Underscores are ignored
c = bitarray([True, False, True, True])
print(f"Bitarray from string: {b}")
print(f"Bitarray from list: {c}")
# Perform bitwise operations
d = b & c # Bitwise AND
e = b | c # Bitwise OR
print(f"Bitwise AND (b & c): {d}")
print(f"Bitwise OR (b | c): {e}")