This content originally appeared on DEV Community and was authored by seng
Python bytearray
Overview
bytearray is an important built-in class in Python that represents a mutable sequence of bytes.
1. Basic Characteristics
bytearray is similar to bytes, but unlike bytes, bytearray is mutable.
# Create a bytearray
ba = bytearray(b'Hello')
print(ba) # Output: bytearray(b'Hello')
print(type(ba)) # Output: <class 'bytearray'>
2. Methods to Create bytearray
Create from bytes object
ba1 = bytearray(b'Hello')
print(ba1) # bytearray(b'Hello')
Create from string (encoding required)
ba2 = bytearray('Hello', 'utf-8')
print(ba2) # bytearray(b'Hello')
Create empty bytearray of specified length
ba3 = bytearray(5)
print(ba3) # bytearray(b'\x00\x00\x00\x00\x00')
Create from iterable object
ba4 = bytearray([65, 66, 67, 68]) # ASCII: A, B, C, D
print(ba4) # bytearray(b'ABCD')
3. Mutability Demonstration
# bytes is immutable (will cause error)
b = b'Hello'
# b[0] = 74 # TypeError: 'bytes' object does not support item assignment
# bytearray is mutable
ba = bytearray(b'Hello')
ba[0] = 74 # ASCII code for 'J'
print(ba) # bytearray(b'Jello')
4. Common Operations
Add elements
ba = bytearray(b'Hello')
ba.append(33) # ASCII code for '!'
print(ba) # bytearray(b'Hello!')
Extend bytearray
ba = bytearray(b'Hello')
ba.extend(b' World')
print(ba) # bytearray(b'Hello World')
Convert to other types
ba = bytearray(b'Hello')
# Convert to bytes
bytes_obj = bytes(ba)
print(bytes_obj) # b'Hello'
# Convert to string
string = ba.decode('utf-8')
print(string) # 'Hello'
This content originally appeared on DEV Community and was authored by seng
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.
APA
MLA
seng | Sciencx (2025-10-23T05:06:37+00:00) Python bytearray. Retrieved from https://www.scien.cx/2025/10/23/python-bytearray/
" » Python bytearray." seng | Sciencx - Thursday October 23, 2025, https://www.scien.cx/2025/10/23/python-bytearray/
HARVARDseng | Sciencx Thursday October 23, 2025 » Python bytearray., viewed ,<https://www.scien.cx/2025/10/23/python-bytearray/>
VANCOUVERseng | Sciencx - » Python bytearray. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/10/23/python-bytearray/
CHICAGO" » Python bytearray." seng | Sciencx - Accessed . https://www.scien.cx/2025/10/23/python-bytearray/
IEEE" » Python bytearray." seng | Sciencx [Online]. Available: https://www.scien.cx/2025/10/23/python-bytearray/. [Accessed: ]
rf:citation » Python bytearray | seng | Sciencx | https://www.scien.cx/2025/10/23/python-bytearray/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.