89DEVs

Python bytearray() function

The Python function bytearray() returns the a bytearray object of the given value. While bytes are immutable, the bytearray object is actually mutable.

bytearray() on list

example = [2, 5, 11] print(bytearray(example)) This example returns the following bytearray: bytearray(b'\x02\x05\x0b')

bytearray() on string

If bytearray() is used on strings, it is necessary to pass the optional encoding argument in the second position. If the encoding is not passed a TypeError exception is raised. string1 = 'Python is awesome!' print(bytearray(string1, 'utf-8')) This example returns the following bytearray: bytearray(b'Python is awesome!') It is possible to use a different encoding, for example UTF-16: string1 = 'Python is awesome!' print(bytearray(string1, 'utf-16')) This returns us the following bytearray: bytearray(b'\xff\xfeP\x00y\x00t\x00h\x00o\x00n\x00 \x00i\x00s\x00 \x00a\x00w\x00e\x00s\x00o\x00m\x00e\x00!\x00')

bytearray() on iterable list

If we use bytarray() on an iterable list, it returns the bytearray with binary representation of the values. list1 = [0, 1, 2, 3, 4, 5] print(bytearray(list1)) In this example Python returns the following bytearray: bytearray(b'\x00\x01\x02\x03\x04\x05') The len() function is used to count the bytes: list1 = [0, 1, 2, 3, 4, 5] print(len(bytearray(list1))) The size of the bytearray is returned: 6

bytearray() on integers

If we use the bytearray() function on an integer, it returns an array of the given size with null values. int1 = 3 print(bytearray(int1)) In this example a bytearray of size 3 is returned: bytearray(b'\x00\x00\x00')

bytearray() syntax

The syntax of the bytearray() function is: bytearray([object], [encoding], [errors])

bytearray() arguments

The bytearray() function takes three optional arguments: source, to initialize the bytearray encoding, to define the encoding of the string errors, to define an action when encoding fails If the first argument is a string, then the encoding argument is required. If no argument is passed, an empty bytearray is returned: bytearray(b'')

bytearray() return value

The bytearray() function returns an bytearray of the given arguments. If an integer is used as first argument, the integer is the size of the bytearray initialized as null.

bytearray() alternative

The bytearray() function creates an bytearray. This object is mutable and can be modified. If an immutable object is desired, the bytes() function is more useful.

                
        

Summary


Click to jump to section