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'
Top comments (0)