Python bytearray() Method with Examples

In this article, we will learn about python bytearray() method with examples. We will see how to use this method to create array of bytes.

Getting Started

As per official documentation,
bytearray() method returns a new array of bytes. bytearray is mutable sequence of intergers in the range of 0 to 256.

Syntax of bytearray() Method

Syntax of bytearray() method in python is –

bytearray(source, encoding, errors)

Where,

  • source: A source which is used to create and initialise array of bytes.
  • encoding: If the source is string, encoding of the string.
  • errors: Action to be taken when encoding of the string fails.

Parameter of bytearray() Method

As discussed above, bytearray() method takes 3 arguments – source, encoding and errors.

Some points to remember –

  • If the source is a string, we must provide encoding parameter.
  • If the source is an integer, new array will have that size and it will be initialised with null.
  • If the source is iterable object e.g. python list, it must have integer elements only ranging from 0 to 256.
  • If the source is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialise the bytes array.
  • If there is no source, array of size 0 will be initialised.

Return Value of bytearray() Method

bytearray() method returns a new array of bytes created using source and encoding provided as arguments.

Examples of bytearray() Method

Now, we will have different examples on bytearray() method in python –

  • Example 1: Creates array of bytes from String Source

    If the source is string, we can use bytearray() method as below –

    str = "Tutorialwing"
    
    # Creates array of bytes 
    # using encoding utf-8 and utf-16
    
    newArray1 = bytearray(str, 'utf-16')
    newArray2 = bytearray(str, 'utf-8')
    
    print(newArray1)
    print(newArray2)
    

    Output:

    bytearray(b'\xff\xfeT\x00u\x00t\x00o\x00r\x00i\x00a\x00l\x00w\x00i\x00n\x00g\x00')
    bytearray(b'Tutorialwing')
    

    Here,
    We created array of bytes using bytearray() method and encoding with ‘utf-16’ and ‘utf-8’.

  • Example 2: Creates array of bytes from Integer Source

    If the source is integer, bytearray() creates a new array of bytes with that size and initializes it with null value. For example,

     
    size = 10
    
    newArray = bytearray(size)
    print(newArray) 
    

    Output:

     
    bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
    
  • Example 3: Creates array of bytes from Iterable List

    If the source is iterable list, bytearray() creates a new array of bytes and initializes it with elements of list. All items of List must be integer value. For example,

     
    listA = [2, 3, 4, 5]
    
    newArray = bytearray(listA)
    print(newArray)
    

    Output:

    bytearray(b'\x02\x03\x04\x05')
    

    Above code created new array using iterable list as source.

    Example 2

    Let’s take another example,

     
    listA = [2, 3, 4, 500]
    
    newArray = bytearray(listA)
    print(newArray)
    

    Output:

     
    ValueError: byte must be in range(0, 256)
    

    We got this error because all elements of list must be in range of 0 to 256.

    Example 3:

    Let’s take another example,

     
    listA = [2, 3, 4, 5.0]
    
    newArray = bytearray(listA)
    print(newArray) 
    

    Output:

     
    TypeError: 'float' object cannot be interpreted as an integer 
    

    We got this error because all items of list must be integer value. 5.0 is not a integer value. Hence, we get error.

  • Example 4: Creates array of bytes from Object

    If source is an object, read-only buffer will be used to create array of bytes. For example,

     
    # Creates bytearray from byte literal
    newArray1 = bytearray(b"hello")
      
    # iterating the value in newArray1
    for value in newArray1:
        print(value)
          
    # Create a bytearray object
    newArray2 = bytearray(b"Tutorialwing")
    
    # Counts bytes from the buffer
    print("Count of i is:", newArray2.count(b"i"))
    

    Output:

     
    104
    101
    108
    108
    111
    Count of i is: 2
    
  • Example 5: Creates array of bytes from Empty Source

    When source is empty, bytearray() method creates a new array of bytes with size 0. For example,

    # Creates bytearray from empty source
    newArray1 = bytearray()
    print(newArray1)
    

    Output:

    bytearray(b'')
    

Learn more at official doc.

That’s end of our post on python bytearray() method with examples.

Leave a Reply