Remove first n elements of bytes object without copying

Viewed 17295

I want to remove elements of a bytes parameter in a function. I want the parameter to be changed, not return a new object.

def f(b: bytes):
  b.pop(0)   # does not work on bytes
  del b[0]   # deleting not supported by _bytes_
  b = b[1:]  # creates a copy of b and saves it as a local variable
  io.BytesIO(b).read(1)  # same as b[1:]

What's the solution here?

2 Answers

Using a bytearray as shown by @MSeifert above, you can extract the first n elements using slicing

>>> a = bytearray(b'abcdef')
>>> a[:3]
bytearray(b'abc')
>>> a = a[3:]
a
bytearray(b'def')
Related