Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bytes vs bytearray in Python 2.6 and 3

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 ints:

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?

like image 235
Craig McQueen Avatar asked Nov 16 '09 07:11

Craig McQueen


People also ask

What is the difference between bytes and Bytearray in Python?

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.

What is Bytearray data type in Python?

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.

What is the difference between bytes and string in Python?

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.

What is byte size in Python?

bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256 .


1 Answers

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.

like image 58
arshbot Avatar answered Oct 05 '22 22:10

arshbot