bytearray() Mutable byte sequence
Last updated: 2026-09-22
bytearray() Mutable byte sequence
bytearray() returns a mutable array of bytes; each element is an integer in 0–255.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
bytearray([source[, encoding]]]])
⚙️ Parameters
| source Optional | Optional: an int (length), string, iterable of ints, or bytes-like object.(Default:None) |
|---|---|
| encoding Optional | Encoding name used when source is a str, e.g. 'utf-8'.(Default:None) |
| errors Optional | Error-handling scheme for encoding, e.g. 'strict' / 'ignore'.(Default:None) |
Returns:bytearray. A mutable byte array whose elements are ints 0-255.
💥 Raises
TypeError— Raised when source has an unsupported type.ValueError— Raised when an element is outside 0-255 or the encoding is invalid.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
bytearray(b'Hello')
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between bytearray and bytes?
Abytearray is mutable (you can change elements, append, and slice-assign), while bytes is immutable; both hold integers from 0-255.
QWhy must I pass an encoding when creating a bytearray from a string?
AA string holds characters, not bytes, so you must specify an encoding (e.g. 'utf-8') to convert to bytes. bytearray('中文') without an encoding raises a TypeError.
QWhat type are the elements of a bytearray?
AThey are integers from 0-255, e.g. bytearray(b'hello')[0] returns 104, not 'h'; use chr() to convert back to a character.
QCan an element exceed 0-255?
ANo. Assigning an out-of-range value (e.g. ba[0] = 256) raises a ValueError.