bytearray

The built-in bytearray data type provides a mutable sequence of bytes, allowing for efficient manipulation of binary data. The bytearray objects are mutable, making them suitable for tasks that require frequent changes to byte data:

Python
>>> data = bytearray(b"Hello, World!")
>>> data
bytearray(b'hello, World!')

bytearray Constructors

Python Syntax
bytearray(source=b"")
bytearray(source, encoding)
bytearray(source, encoding, errors)

Arguments

Argument Description Default Value
source A bytes literal, string, integer, buffer, or iterable of integers b""
encoding The character encoding to use if source is a string Required argument
errors A handler for encoding/decoding errors "strict"

Return Value

  • Returns a Python bytearray object

bytearray Examples

Creating an empty bytearray using the constructor without arguments:

Python
>>> bytearray()
bytearray(b'')

Creating a bytearray using a bytes literal as an argument:

Python
>>> bytearray(b"Hello!")
bytearray(b'Hello!')

Creating a bytearray from a string with encoding:

Python
>>> bytearray("Español", "utf-8")
bytearray(b'Espa\xc3\xb1ol')

Accessing and modifying values in a bytearray object:

Python
>>> greeting = bytearray(b"Hello!")
>>> greeting[0] = ord("h")
>>> greeting
bytearray(b'hello!')

Deleting a value from a bytearray object:

Python
>>> del greeting[-1]
>>> greeting
bytearray(b'hello')

bytearray Methods

Method Description
.append(x) Appends a single item x to the end
.extend(iter) Extends the array by appending elements from iter
.insert(i, x) Inserts an item x at position i
.remove(x) Removes the first occurrence of x
.pop([i]) Removes and returns the item at position i (last if not specified)
.clear() Removes all items
.copy() Returns a shallow copy of the array
.count(x) Returns the number of occurrences of x
.index(x[, start[, end]]) Returns the index of the first occurrence of x
.reverse() Reverses the items of the array in place
.sort() Sorts the items of the array in place

bytearray Common Use Cases

The most common use cases for the bytearray include:

  • Manipulating binary data
  • Encoding and decoding text data
  • Processing file input and output
  • Network communication

bytearray Real-World Example

Consider a scenario where you need to replace all occurrences of a specific byte value in a file’s content:

Python
>>> file_content = bytearray(b"This is a test. Testing is fun!")
>>> old_byte = ord('t')
>>> new_byte = ord('T')

>>> for i in range(len(file_content)):
...     if file_content[i] == old_byte:
...         file_content[i] = new_byte

>>> print(file_content)
bytearray(b"This is a TesT. TesTing is fun!")

In this example, the bytearray allows for efficient in-place modification of the file’s content, making it ideal for scenarios that involve frequent updates to binary data.

Tutorial

Basic Data Types in Python: A Quick Exploration

In this tutorial, you'll learn about the basic data types that are built into Python, including numbers, strings, bytes, and Booleans.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 6, 2024 • Reviewed by Dan Bader