Remember
bytearray() creates a mutable sequence of bytes. Each element must be an integer from 0 through 255.
bytearray() creates a mutable sequence of bytes. Each element must be an integer from 0 through 255.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
data = bytearray([3, 66])
data[0] = 65
print(list(data))Top-level scope
bytearray(b'AB')bytearray() creates a mutable sequence of bytes. Each element must be an integer from 0 through 255.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
data = bytearray([3, 66])
data[0] = 65
print(list(data))
|
v
DISPLAYED RESULT
[65, 66]
FINAL BINDINGS
data --> object 1 (bytearray)
object 1: bytearray(b'AB')Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
data = bytearray([3, 66])
data[0] = 65
print(list(data))Top-level scope
bytearray(b'AB')The example has finished. Compare the final output with the values and references above.
[65, 66]
What do you expect this program to print?
data = bytearray([3, 66])
data[0] = 65
print(list(data))bytearray() FunctionThe bytearray() function in Python is used to create a mutable sequence of bytes. It’s like a list, but each item is a byte (0 to 255). This is useful when you want to manipulate binary data such as files, images, or streams.
bytearray([source[, encoding[, errors]]])
source (optional) – can be a string, bytes, iterable of integers, or an integer size.encoding (optional) – required if the source is a string.errors (optional) – how to handle encoding errors ('strict', 'ignore', etc.).b = bytearray()
print(b)
bytearray(b'')
b = bytearray([65, 66, 67])
print(b)
bytearray(b'ABC')
b = bytearray("hello", "utf-8")
print(b)
bytearray(b'hello')
b = bytearray("hello", "utf-8")
b[0] = 72 # Replace 'h' with 'H'
print(b)
bytearray(b'Hello')
In low-level system or network programming, you may be asked to handle binary protocols. Knowing bytearray() is essential when you need mutable binary structures.
bytearray() creates a mutable array of bytes.Write a program that converts a user-entered string into a bytearray, modifies the first character, and prints the result.
text = input("Enter a word: ")
b = bytearray(text, "utf-8")
b[0] = b[0] - 32 # Make first character uppercase
print("Modified:", b)
Connect what you noticed in the example with the idea below.
bytearray() creates a mutable sequence of bytes. Each element must be an integer from 0 through 255.
A bytearray cannot be changed after creation.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.