Table of content

Python Bytes and Bytearray

Bytes: A byte is a unit of digital information that most commonly consists of eight bits.

ex: 1 byte= 8 bits, kilobyte, gigabyte, terabyte, etc..

Bytearray: An array of bytes is called as bytearray.

Ex: we can use a bytearray to store a collection of binary data.

Python Bytes : Python supports a range of types to store sequences like bytes and bytearray functions, where byte() the method returns immutable bytes object initialized with the given size and data.

Python Bytearray : bytearray() the method returns a bytearray object which is an array of given bytes.

If you want to represent a group of byte values then we can go to Byte Datatype.

Ex: L=[10,20,25,30,35] and if you want to create a byte object then you should call an inbuilt function called bytes(L) that is b= bytes(L) and if you print(type(b)) then you are going to get an answer as bytes data type

L[10,20,25,30,35]
b=bytes(L)
print(type(b))

byte-function

And if you want to print all the values present inside the list, by using the command, for each value x in b, print(x)

for x in b :
print(x)

printing-each-value-in-b

Conclusion of Byte Datatype

  • Bytes Datatype can represent the value from 0 to 255 only and if you trying to create a bytes values more than this, then you are going to get an error
    L=[10,20,52,256]
    b=bytes(L)
    print(type(b))​

    byte-exceed-value-error

  • The bytes Datatypes are Immutable, once we create any list, we cannot make any changes to its content.
    L=[10,15,20,25]
    b=bytes(L)
     print(b[0])=  ?
    b[0]=8
    
    
    ​

    byte-datatype-is-immutable

Bytearray Datatype:

Bytearray is almost similar to the byte Datatype except for the thing that it is Mutable

L=[10,20,25,32,42]
b=bytearray(L)
print(b[0])= ?
print(b[-1])= ?

bytearray-fnction

Bytearray datatype is also iterable in the range between 0 to 256, that means the content value should be between 0 and 255 or else you will get a value error

L=[10,25,85,255]
b=bytearray(L)
print(type(b))
print(b[0])
print(b[-1])


bytearray-operations

Let us change the content of the object

L=[10,20,50]
b=bytearray(L)
print(b[0])= ?
b[0]=11
for x in b:
print(x)

The content of the object is under the limit range, then the output is

bytearray-is-mutable

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions