Array¶
The Array class is used as a container for contiguously allocated Bits objects with the same Dtype.
Array instances act very like an ordinary Python array, but with each element being a fixed-length dtype.
They are mutable, so values can be changed after creation.
- class Array(dtype: str | Dtype, iterable: Iterable | None = None)¶
An Array whose elements are all a single data type.
The
Arraydata is stored compactly as aMutableBitsobject and theArraybehaves very like a list of items of the given format.If the data length is not a multiple of the dtype length then the
Arraywill havetrailing_bitswhich will prevent some methods from appending to theArray.To construct, use a builder ‘from’ method:
Array.from_iterable(dtype, iterable)- Create and initialise from an iterable.Array.from_bits(dtype, bits)- Create with data from aBitsorMutableBitsobject.Array.from_bytes(dtype, bytes_data)- Create with data from abytes-like object.Array.from_zeros(dtype, n)- Initialise with enough zero bits fornelements.
Using the constructor
Array(dtype, iterable)is an alias forArray.from_iterable(dtype, iterable), but this does not accept eitherBitsorbytesobjects as the iterable to avoid confusion.Other methods:
append(item): Append a single item to the end of the Array.as_type(dtype): Creates a new Array with a new data type, initialized from the current Array.byte_swap(): Change byte endianness of all items.count(value): Count the number of occurrences of a value.equals(other): Comparison method between Arrays.extend(iterable): Append new items to the end of the Array from an iterable.insert(index, item): Insert an item at a given position.pop([index]): Remove and return an item. Default is the last item.pp([dtype1, dtype2, groups, width, show_offset, stream]): Pretty print the Array.reverse(): Reverse the order of all items.to_bits(): Return a copy of the Array data as an immutableBits.to_bytes(): Return Array data as bytes object, padding with zero bits at the end if needed.to_list(): Return Array items as a list of values.
Special methods:
Also available are the operators
[],==,!=,+,*,<<,>>,&,|,^, plus the mutating operators[]=,+=,*=,<<=,>>=,&=,|=,^=.Properties:
bits: The binary data of theArrayas aMutableBitsobject.dtype: The data type of the elements in theArray.item_size: The length in bits of a single item. Read only.trailing_bits: If the data length is not a multiple of the dtype length, thisBitsgives the leftovers at the end of the data.
- append(x, /)¶
Append a single item to the end of the Array.
- Parameters:
x (
Union[float,str,int,bytes,bool,Bits,MutableBits]) – The item to append.- Return type:
- Returns:
The modified Array.
- as_type(dtype, /)¶
Creates and returns a new
Arrayinstance with a specified data type, initialized with the current Array’s elements.This method allows for the conversion of the Array’s elements to a different data type, specified by the
dtypeparameter. The conversion process respects the original values of the elements, adapting them to the new data type format. This can be useful for changing the representation of data within the Array, for example, from integers to floating-point numbers or vice versa.- Parameters:
dtype (
str|Dtype) – The target data type for the new Array.- Return type:
- Returns:
A new
Arrayinstance with the specifieddtype, containing the elements of the current Array converted to the new data type.- Raises:
ValueError – If the specified
dtypeis not supported or cannot be applied to the elements of the current Array.
>>> original_array = Array('i5', [1, 2, 3]) >>> float_array = original_array.as_type('f16') >>> print(float_array) Array('f16', [1.0, 2.0, 3.0])
- byte_swap()¶
Change the endianness in-place of all items in the Array.
- Return type:
- Returns:
The modified Array.
- Raises:
ValueError – If the Array format is not a whole number of bytes.
- count(value, /)¶
Return count of Array items that equal value.
- Parameters:
value (
Union[float,str,int,bytes,bool,Bits,MutableBits]) – The quantity to compare each Array element to. Type should be appropriate for the Array format.- Return type:
int
For floating point types using a value of
float('nan')will count the number of elements that are NaN.
- equals(other, /)¶
Return True if the data type and all Array items are equal to another Array.
This method should be used to test the equality of two Arrays. Normally types will provide an
==operator to do this task, but for Arrays the==operator is instead used for element-wise comparison and will return a new Array of bools.- Parameters:
other (
Any) – The other Array to compare with.- Return type:
bool- Returns:
Trueif the Arrays are equal,Falseotherwise.
- extend(iterable, /)¶
Append new items to the end of the Array from an iterable.
This method allows you to extend the Array by appending elements from another iterable. The iterable can be another Array, bytes, bytearray, Bits, or any other iterable containing elements of a compatible type.
- classmethod from_bytes(dtype, bytes_data)¶
Create a new
Arrayfrom a data type and a bytes object.- Parameters:
- Return type:
a = Array.from_bytes('u8', b"some_bytes_maybe_from_a_file")
- info()¶
Return a descriptive string with information about the Array.
Note that the output is designed to be helpful to users and is not considered part of the API. You should not use the output programmatically as it may change even between point versions.
- Return type:
str
- insert(pos, x, /)¶
Insert a new element into the Array at position pos.
- Parameters:
pos (
int) – The position to insert the item.x (
Union[float,str,int,bytes,bool,Bits,MutableBits]) – The item to insert.
- Return type:
- Returns:
The modified Array.
- pop(pos=-1, /)¶
Return and remove an element of the Array.
Default is to return and remove the final element.
- Parameters:
pos (
int) – The position of the item to remove. Default is -1 (last item).- Return type:
Union[float,str,int,bytes,bool,Bits,MutableBits]- Returns:
The removed item.
- pp(dtype1=None, dtype2=None, groups=None, width=80, show_offset=True, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)¶
Pretty-print the Array contents.
This method provides a formatted output of the Array’s contents, allowing for easy inspection of the data. The output can be customized with various parameters to control the format, width, and display options.
- Parameters:
dtype1 (
str|Dtype|None) – Data type to display. Defaults to the current Array dtype.dtype2 (
str|Dtype|None) – Data type for addition display data.groups (
int|None) – How many groups of bits to display on each line. This overrides any value given for width.width (
int) – Maximum width of printed lines in characters. Defaults to 80, but ignored if groups parameter is set. A single group will always be printed per line even if it exceeds the max width.show_offset (
bool) – If True, shows the element offset in the first column of each line.stream (
TextIO) – A TextIO object with a write() method. Defaults to sys.stdout.
- Return type:
None- Returns:
None
- reverse()¶
Reverse the order of all items in the Array in place.
- Raises:
ValueError – If the Array’s data length is not a multiple of the item size in bits.
- Return type:
- Returns:
The Array object with its items reversed.
>>> a = Array('i14', [-3, 0, 100]) >>> a.reverse() Array('i14', [100, 0, -3])
- to_bits()¶
Return as a Bits object. This is an immutable copy of the current Array data.
- Return type:
- to_bytes()¶
Return the Array data as a bytes object, padding with zero bits if needed.
Up to seven zero bits will be added at the end to byte align.
- Return type:
bytes
- to_list(dtype=None)¶
Interpret the Array as a list of elements of a given dtype, defaulting to the Array’s current dtype.
>>> a = Array('i3', [2, 1, -2, 0]) >>> a.to_list() [2, 1, -2, 0] >>> a.to_list('bin3') ['010', '001', '110', '000'] >>> a.to_list('u5, bool') [(8, True), (24, False)]
- Return type:
list[Union[float,str,int,bytes,bool,Bits,MutableBits]]
- property bits: MutableBits¶
Property that provides access to the
Arraydata as aMutableBits.Note that this is the actual data of the
Arrayand any changes made to it will affect theArray. Use theto_bitsmethod if you need a copy of the data instead.
- property item_size: int¶
The length of a single item in bits. Read only.