Function Details: bytearray

Description


Returns a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256.


Extended Description


The bytearray() function creates a mutable sequence of bytes. It can be initialized in various ways: from an iterable of integers, from a string with a specified encoding, from bytes or another bytearray object, or by creating an array of null bytes of a specified length.


Exceptions


  • ValueError: If any integer in the iterable is outside the range 0 <= x < 256
  • TypeError: If the source argument has an inappropriate type

Read More about bytearray from Python Documentation

Function Signature


bytearray(source: Union[int, Iterable[int], str, bytes] = None, encoding: str = None, errors: str = None) -> bytearray

Module: builtins

Parameters


source: Can be an integer (to create that many null bytes), an iterable of integers 0 <= x < 256, a string (requires encoding to be specified), or an object that implements the buffer protocol (like bytes). encoding: The encoding to use if source is a string. Common values include 'utf-8', 'ascii', etc. errors: Specifies how to handle encoding errors. Common values are 'strict', 'ignore', 'replace', etc.


Parameter List


  • source: Union[int, Iterable[int], str, bytes]
  • encoding: str
  • errors: str

Return


Returns a new bytearray object, which is a mutable sequence of integers in the range 0 <= x < 256.


Return Type


bytearray

Output

Explanation

This example shows how to create bytearrays from an iterable of integers, a string with encoding, and an integer (creating null bytes).