The zfill() method of bytearray class in Python

The zfill() method returns a bytearray of a specified length by prefixing the copy of the bytearray with zeroes. If the specified length is less than the original size than a copy of the bytearray is returned without any zero-prefixing.

Bytearray Updated 11 Nov 2025 2 min read

Overview

The zfill() method returns a new bytearray object of a given size which is zero-filled on the left side. The zfill() returns a zero padded bytearray on the left side, only when the given size is greater than the current size of the bytearray. If the given size is less than the current size, a copy of the original bytearray is returned without any modification.

The zfill() method of bytearray in Python

Though the resize() and zfill() methods are about changing the size of a bytearray the following are the differences between them:

The zfill() methodThe resize() method
When buffer less than current sizeWhen a size less than the current size is specified the zfill() method returns the copy of the original bytearray.The reset method will reduce the size of the original bytearray when a size less than the current size is specified.
Zero fill locationThe zfill() method zero-fills on the left side of the bytearray and returns the new bytearray. The original bytearray is not modified.When the size given is greater than current size it zero-fills the left side of the original bytearray.
Copy vs actual bytearrayChanges are made to the copy of the bytearray.Changes are made to the original bytearray.

Example

python
# Example Python program that creates a new

            # bytearray of greater length which is zero-filled

            # on the front

# Create a bytearray

            buffer     = bytearray(b"The lazy brown fox")

# Create a new bytearray which is zfilled

            # on the front

            zfilled = buffer.zfill(len(buffer) + 4)

print("Original bytearray:")

            print(buffer)

            print("Id:{}".format(id(buffer)))

print("The zfilled bytearray:")

            print(zfilled)

            print("Id:{}".format(id(zfilled)))

Output

Output
Original bytearray:

            bytearray(b'The lazy brown fox')

            Id:4340038960

            The zfilled bytearray:

            bytearray(b'0000The lazy brown fox')

            Id:4340038896