Code Explanation:
๐น 1. Creating a bytearray
data = bytearray(b"Python")
✅ Explanation
bytearray() creates a mutable sequence of bytes.
The prefix b means the text is stored as bytes, not as a normal string.
Unlike Python strings, a bytearray can be modified.
Current Memory
data
↓
bytearray(b'Python')
Visual Representation
Index
0 1 2 3 4 5
↓
P y t h o n
๐น 2. Understanding bytearray
✅ Explanation
A normal string cannot be modified.
Example:
text = "Python"
text[0] = "J"
Output
TypeError
But a bytearray allows individual bytes to be changed.
Current object:
bytearray
↓
P
y
t
h
o
n
๐น 3. Creating a Memory View
view = memoryview(data)
✅ Explanation
memoryview() creates a view of the original object.
It does not create a copy.
Instead, both variables point to the same memory.
Memory Diagram
bytearray
▲
│
data ─────────┘
▲
│
view ─────────┘
Think of memoryview as a window through which you can directly access the original data.
๐น 4. Understanding memoryview
✅ Explanation
Since view and data share the same memory:
Changing view
Automatically changes data
There are not two separate objects.
Current Memory
data
↓
P y t h o n
▲
│
view
๐น 5. Accessing the First Byte
view[0]
✅ Explanation
Index 0 points to the first byte.
Current bytes:
Index
0 1 2 3 4 5
↓
P y t h o n
Index 0 contains:
P
๐น 6. Using ord("J")
ord("J")
✅ Explanation
ord() converts a character into its ASCII (Unicode) integer value.
Calculation:
Character
J
↓
ASCII Value
74
So Python actually executes:
view[0] = 74
๐น 7. Replacing the First Byte
view[0] = ord("J")
✅ Explanation
Python replaces the first byte.
Before
P y t h o n
After
J y t h o n
Since view and data share memory, the original bytearray also changes.
Current Memory
data
↓
bytearray(b'Jython')
๐น 8. Decoding the Bytes
data.decode()
✅ Explanation
decode() converts bytes into a normal Python string.
Before decoding
bytearray(b'Jython')
After decoding
"Jython"
The bytes are converted into readable text.
๐น 9. Printing the Result
print(data.decode())
✅ Explanation
Python prints the decoded string.
Output
Jython
๐ฏ Final Output
Jython

0 Comments:
Post a Comment