Python Reference ยท Built-in Functions
Python bytearray() function
Reference for Python bytearray(): create a mutable sequence of bytes from a size, an iterable, a string with an encoding or a buffer, then edit it in place.
bytearray is the mutable counterpart of bytes: a sequence of integers from 0 to 255 that you can change in place. You can assign to single items and slices, append, extend, insert and delete, which makes it a good buffer for building or editing binary data piece by piece.
Calling bytearray() creates one from a size, an iterable of integers, a string plus an encoding, or any object supporting the buffer protocol.
buf = bytearray(b"abc") buf[0] = 65 # bytearray(b'Abc')
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
bytearray() bytearray(source) bytearray(source, encoding) bytearray(source, encoding, errors)
| Name | Description |
|---|---|
source |
An int (that many zero bytes), an iterable of integers 0-255, a str (needs encoding), or an object with a buffer such as bytes or memoryview. |
encoding |
Required when source is a str, for example "utf-8". |
errors |
How to handle unencodable characters: "strict" (default), "ignore", "replace", ... |
Return value: a new bytearray.
Raises: TypeError if a string is given without an encoding; ValueError if an item is outside 0-255; OverflowError or ValueError for a negative size.
Usage notes
- Items are integers.
data[0]is anint(for example104), not a one-byte string. A slice such asdata[0:1]is abytearray. - Methods. It has most
bytesmethods (find,split,replace,hex,decode, ...) plus the mutable list-like ones:append,extend,insert,pop,remove,reverse,clear,copy. - Copies vs views.
bytes(data)makes an immutable copy.memoryview(data)gives a zero-copy view you can slice and write through; the bytearray cannot be resized while a view exists. - Not hashable. Because it is mutable, a
bytearraycannot be a dictionary key or set member. Convert tobytesfirst. - Efficient appends. Repeated
+=on abytearrayis amortized fast; repeated+onbytescopies every time. - Text. Decode with
.decode("utf-8"). A multi-byte character split across edits will fail to decode. - Binary files.
file.readinto(buffer)fills a preallocatedbytearraywithout allocating a new object each read.
Related
bytes(),memoryview(),chr(),ord(),str.encode()- Lessons: Strings, Files, Data types