Table of Contents | |
Understanding Python bytearray()
Function
Python bytearray() function returns a new array of bytes, which is a mutable sequence of integers in the range 0 <= x < 256.1
. Essentially, it creates a collection of bytes you can modify after making it, unlike an immutable object. You can create a bytearray object from a string (you must provide an encoding for this), an integer (it will create an array of that size, filled with null bytes), or a list of integers. This is especially helpful when dealing with binary data, such as files or network connections, where you might need to change the data on the fly.
Syntax of Python bytearray
()
bytearray
()bytearray_object = bytearray(source, encoding, errors)
Explanation
bytearray_object
: Variable will hold the newbytearray
object that is created.bytearray()
: Function that creates thebytearray
object.source
(optional): Source to initialize the array. This can be a string, integer or a list.encoding
(optional): If the source is a string, this specifies the encoding of the string.errors
(optional): If the source is a string, this specifies what to do if the encoding fails.
Example of Python bytearray
()
bytearray
()bytearray_obj = bytearray()
print(bytearray_obj)
bytearray_obj.append(65)
print(bytearray_obj)
Explanation
bytearray_obj = bytearray()
: Creates an emptybytearray
object namedbytearray_obj
.print(bytearray_obj)
: Prints the emptybytearray
object, which outputsbytearray(b'')
.bytearray_obj.append(65)
: Adds the integer 65 (ASCII for ‘A’) to thebytearray
.print(bytearray_obj)
: Prints the updatedbytearray
, which outputsbytearray(b'A')
.
Output
bytearray(b”)
bytearray(b’A’)
Python bytearray()
with String
When you use Python bytearray() with a string as the source, you must also provide the encoding for that string. The function will then convert the string into a sequence of bytes according to the specified encoding and create a mutable byte array object from it. Standard encodings include ‘utf-8’, ‘ascii’, and ‘latin-1’. This is particularly useful when you need to manipulate text as raw bytes, for instance, when preparing data to be sent over a network or written to a binary file.
Syntax
bytearray_object = bytearray(string, encoding, errors)
Explanation
bytearray_object
: Variable holds thebytearray
object created from the string.bytearray()
: Function creates thebytearray
object.string
: String you want to convert into abytearray
. It is used as input for thebytearray()
function.encoding
: Specifies how the string should be encoded into bytes (e.g., ‘utf-8’).errors
: Optional parameter that specifies how encoding errors should be handled.
Example
string = "Hello"
encoding = "utf-8"
bytearray_string = bytearray(string, encoding)
print(bytearray_string)
Explanation
string = "Hello"
: Assigns the string “Hello” to the variablestring
.encoding = "utf-8"
: Sets the encoding to ‘utf-8’.bytearray_string = bytearray(string, encoding)
: Creates abytearray
fromstring
using the specifiedencoding
and stores it inbytearray_string
.print(bytearray_string)
: Prints thebytearray_string
, which outputsbytearray(b'Hello')
.
Output
bytearray(b’Hello’)
Python bytearray()
with Integer Argument
Using an integer as an argument for Python bytearray() creates a bytearray object of the given size, filled with null bytes (\x00). This means it initializes a mutable sequence of bytes where each byte has a value of 0, and the sequence length is equal to the integer you provided. This can be useful when you need a buffer of a specific size to work with binary data.
Syntax
bytearray_object = bytearray(integer)
Explanation
bytearray_object
: Variable will hold thebytearray
object of the specified size.bytearray()
: Function creates thebytearray
object.integer
: Integer determines the size of thebytearray
to be created. It is used as input for thebytearray()
function.
Example
size = 5
bytearray_int = bytearray(size)
print(bytearray_int)
Explanation
size = 5
: Assigns the integer 5 to the variablesize
.bytearray_int = bytearray(size)
: Creates abytearray
of 5 null bytes and assigns it tobytearray_int
.print(bytearray_int)
: Printsbytearray_int
, which outputsbytearray(b'\x00\x00\x00\x00\x00')
.
Output
bytearray(b’\x00\x00\x00\x00\x00′)
Python bytearray()
with List
You can create a Python bytearray from a list of integers where each integer ranges from 0 to 255. Each integer in the list represents a byte value. The bytearray() function will then create a mutable sequence of bytes corresponding to the integers in the list. This is useful when you have data represented as integers and must convert it into a mutable byte format.
Syntax
bytearray_object = bytearray(list_of_integers)
Explanation
bytearray_object
: Variable will hold thebytearray
object created from the list.bytearray()
: Function creates thebytearray
object.list_of_integers
: List of integers (0-255) that will be converted into abytearray
. It is used as input for thebytearray()
function.
Example
my_list = [65, 66, 67, 68]
bytearray_list = bytearray(my_list)
print(bytearray_list)
Explanation
my_list = [65, 66, 67, 68]
: Creates a list of integers namedmy_list
.bytearray_list = bytearray(my_list)
: Creates abytearray
frommy_list
and assigns it tobytearray_list
.print(bytearray_list)
: Printsbytearray_list
, which outputsbytearray(b'ABCD')
(65-68 are ASCII values for ABCD).
Output
bytearray(b’ABCD’)
Conclusion
Python bytearray() is a handy function for creating and manipulating mutable sequences of bytes in Python. Whether you’re working with strings, integers, or lists of integers, bytearray() provides a way to convert these data types into a byte format that can be modified. Understanding how Python bytearray works with different data types is essential for tasks that involve binary data manipulation, such as file I/O, network programming, and cryptography. You can always get a mutable sequence of bytes using bytearray() function.