Resetting bytearray
Resetting bytearray
How to "reset" bytearray (set all bytes to b'\x00') without being re-allocated?
After doing this function id() should return same value as before.
After doing this function id() should return same value as before.
Re: Resetting bytearray
The obvious solution would be:
Code: Select all
for i in range(len(your_array)):
your_array[i] = 0
Re: Resetting bytearray
One more option is
Code: Select all
arr[:] = b'0' * len(arr)
Re: Resetting bytearray
Does this really not re-allocate the buffer?platforma wrote:One more option isCode: Select all
arr[:] = b'0' * len(arr)
Re: Resetting bytearray
At least not from what I tried on unix port:
Code: Select all
>>> arr = bytearray([1,2,3])
>>> arr
bytearray(b'\x01\x02\x03')
>>> id(arr)
140355047877312
>>> arr[:] = b'0' * len(arr)
>>> arr
bytearray(b'000')
>>> id(arr)
140355047877312
Re: Resetting bytearray
It allocates a new buffer, and then copies it over to the old one.
Re: Resetting bytearray
The below code could be much more memory-efficient, unfortunately it's not working:
Code: Select all
>>> a[:] = (b'0' for i in range(10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NotImplementedError: array/bytes required on right side
Re: Resetting bytearray
I used:
Is that ok, or not?
Code: Select all
tempbuf = bytearray()
# ...
tempbuf[::] = b''
Re: Resetting bytearray
No, that truncates the array to make it 0-element long.
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Resetting bytearray
Code: Select all
$ ./upython
MicroPython v1.8.1-39-gdb4addd on 2016-07-01; linux version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> a = bytearray(10)
>>> id(a)
139728051341376
>>> a[:] = b'\1' * len(a)
>>> id(a)
139728051341376
>>> a
bytearray(b'\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01')
>>> a[:] = b'\0' * len(a)
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> id(a)
139728051341376
>>>
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.