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

PythonBytearray

Python Problem Overview


All the solutions I found were for lists.

Thanks.

Python Solutions


Solution 1 - Python

This will give you 100 zero bytes:

bytearray(100)

Or filling the array with non zero values:

bytearray([1] * 100)

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYanView Question on Stackoverflow
Solution 1 - PythonNed BatchelderView Answer on Stackoverflow
Solution 2 - PythonAXOView Answer on Stackoverflow