I'm experimenting with bytes
vs bytearray
in Python 2.6. I don't understand the reason for some differences.
A bytes
iterator returns strings:
for i in bytes(b"hi"): print(type(i))
Gives:
<type 'str'> <type 'str'>
But a bytearray
iterator returns int
s:
for i in bytearray(b"hi"): print(type(i))
Gives:
<type 'int'> <type 'int'>
Why the difference?
I'd like to write code that will translate well into Python 3. So, is the situation the same in Python 3?
The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size. The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.
The bytearray type is a mutable sequence of integers in the range between 0 and 255. It allows you to work directly with binary data. It can be used to work with low-level data such as that inside of images or arriving directly from the network. Bytearray type inherits methods from both list and str types.
Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.
bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256 .
For (at least) Python 3.7
According to the docs:
bytes
objects are immutable sequences of single bytes
bytearray
objects are a mutable counterpart to bytes objects.
And that's pretty much it as far as bytes
vs bytearray
. In fact, they're fairly interchangeable and designed to flexible enough to be mixed in operations without throwing errors. In fact, there is a whole section in the official documentation dedicated to showing the similarities between the bytes
and bytearray
apis.
Some clues as to why from the docs:
Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With