9

Below is a sample interaction in Python 3.3

>>> bArray = bytes(b'ABCDE')
>>> bArray
b'ABCDE'
>>> bArray[0]
65
>>> type(bArray[0])
<class 'int'>
>>> bArray[0:1]
b'A'
>>> type(bArray[0:1])
<class 'bytes'>
>>> struct.pack('B', bArray[1])
b'B'
>>> type(struct.pack('B', bArray[1]))
<class 'bytes'>

It shows that indexing a bytes array yields an integer while slicing the same returns a bytes object.

  1. Can anyone please explain me why is it so? Shouldn't indexing, too, return a byte object?
  2. Is using byte more memory/performance efficient that using plain integers, provided the application is guaranteed to use numbers [0,255]?

1 Answer 1

10
  1. A quote from the manual

Warning While string objects are sequences of characters (represented by strings of length 1), bytes and bytearray objects are sequences of integers (between 0 and 255), representing the ASCII value of single bytes. That means that for a bytes or bytearray object b, b[0] will be an integer, while b[0:1] will be a bytes or bytearray object of length 1. The representation of bytes objects uses the literal format (b'...') since it is generally more useful than e.g. bytes([50, 19, 100]). You can always convert a bytes object into a list of integers using list(b).

So there is no "byte" object anymore.

  1. The only explanation I could find was that bytes sequences are more memory efficient and less computation efficient - because all operations require conversion to ints anyway (even internally)
Sign up to request clarification or add additional context in comments.

2 Comments

it might be that bytes (byte sequences) are hashable, compared to a list of integers (0-255) ? Then again, a tuple of integers (0-255) should be hashable.
BTW, I agree that it is confusing. I too expected a single index to produce 1 item of the same type of the array, not an integer .... sigh !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.