Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a bytes or bytearray of given length filled with zeros in Python?

All the solutions I found were for lists.

Thanks.

like image 885
Yan Avatar asked Feb 07 '12 21:02

Yan


People also ask

How do you find the length of a Bytearray in Python?

To find the length of a bytes object in Python, call len() builtin function and pass the bytes object as argument. len() function returns the number of bytes in the object.

What is byte and Bytearray in Python?

python3's bytes and bytearray classes both hold arrays of bytes, where each byte can take on a value between 0 and 255. The primary difference is that a bytes object is immutable, meaning that once created, you cannot modify its elements. By contrast, a bytearray object allows you to modify its elements.


2 Answers

This will give you 100 zero bytes:

bytearray(100) 

Or filling the array with non zero values:

bytearray([1] * 100) 
like image 109
Ned Batchelder Avatar answered Oct 05 '22 04:10

Ned Batchelder


For bytes, one may also use the literal form b'\0' * 100.

# Python 3.6.4 (64-bit), Windows 10 from timeit import timeit print(timeit(r'b"\0" * 100'))  # 0.04987576772443264 print(timeit('bytes(100)'))  # 0.1353608166305015 

Update1: With constant folding in Python 3.7, the literal from is now almost 20 times faster.

Update2: Apparently constant folding has a limit:

>>> from dis import dis >>> dis(r'b"\0" * 4096')   1           0 LOAD_CONST               0 (b'\x00\x00\x00...')               2 RETURN_VALUE >>> dis(r'b"\0" * 4097')   1           0 LOAD_CONST               0 (b'\x00')               2 LOAD_CONST               1 (4097)               4 BINARY_MULTIPLY               6 RETURN_VALUE 
like image 21
AXO Avatar answered Oct 05 '22 05:10

AXO