Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

Python – Find Byte Array Object – bytearray() Function with Examples

bytearray() function is used to find the bytearray object in Python for the given inputs. The bytearray object is the mutable sequence of integers in the range of 0 <=x < 256. Where mutable sequence means the sequence that can be change. For finding Immutable Bytes Object use bytes() function.
bytearray() function is a part of Python Built-in Functions (check list)

Syntax of bytearray() Function

The syntax of bytearray() function in Python is:


Parameters of bytearray() Function in Python

source – Where source is the source who initialize the array of bytes.
encoding – Where encoding is the encoding of the string if the source is a string.
errors – Where errors is the action we want to perform when string encoding will fail. We use errors if source is a string.All three parameters are optional.We can use string, integer and objects etc as a source of bytearray().

StringConverts the string to bytes using str.encode() Must also provide encoding and optionally errors
IntegerCreates an array of provided size, all initialized to null
ObjectRead-only buffer of the object will be used to initialize the byte array
IterableCreates an array of size equal to the iterable count and initialized to the iterable elements Must be iterable of integers between 0 <= x < 256
No source (arguments)Creates an array of size 0.



bytearray() function is available and compatible with both Python 2.x and 3.x.


Return Value of bytearray() Function in Python

bytearray() function returns a bytearray object which is a mutable sequence of integers(that can be change) in the range of 0 <=x < 256 for the given inputs.For returning an immutable sequence use the bytes() function of Python built-in Library.


Python bytearray() Function Example 1

Find array of bytes from a string.

bytearray(b'This is my Test String.')


Python bytearray() Function Example 2

Find array of bytes of given integer size.



Python bytearray() Function Example 3

Find array of bytes from an iterable list.



LearnAndLearn.com © 2018 - All rights reserved