Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first n elements of bytes object without copying

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?

like image 210
yspreen Avatar asked Sep 03 '25 02:09

yspreen


2 Answers

Just use a bytearray:

>>> a = bytearray(b'abcdef')
>>> del a[1]
>>> a
bytearray(b'acdef')

It's almost like bytes but mutable:

The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.

like image 161
MSeifert Avatar answered Sep 04 '25 19:09

MSeifert


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')
like image 42
Ant Avatar answered Sep 04 '25 20:09

Ant