1.

What is the difference between bytes() and bytearray() in Python?

Answer»

Both are built-in functions in STANDARD library. Both functions return sequence objects. However, bytes() returns an immutable sequence, whereas bytearray is a mutable sequence.

The bytes() function returns a bytes object that is an immutable sequence of integers between 0 to 255.

>>> #if argument is an int, creates an array of given size, initialized to null >>> x=10 >>> y=bytes(x) >>> y b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>> type(y) <class 'bytes'>

If string object is used with bytes() function, you should use encoding parameter, default is ‘utf-8’

>> string='Hello' >>> x='Hello' >>> y=bytes(x,'utf-8') >>> y b'Hello'

Note that the bytes object has a literal representation too. Just prefix the string by b

>>> x=b'Hello' >>> type(x) <class 'bytes'>

On the other hand bytearray() returns a mutable sequence. If argument is an int, it INITIALIZES the array of given size with null.

>>> x=10 >>> y=bytearray(x) >>> y bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') >>> type(y) <class 'bytearray'>

However, if the argument is an iterable sequence, array size is equal to iterable count and items are initialized by elements of iterable. Following example shows bytearray object obtained from a list.

>>> x=[2,4,6] >>> y=bytearray(x) >>> y bytearray(b'\x02\x04\x06')

UNLIKE bytes object, a bytearray object doesn’t have literal representation.

Both bytes and bytearray objects support all normal sequence OPERATIONS like find and replace, join and count etc. 

>>> x=b'Hello' >>> x.replace(b'l', b'k') b'Hekko'

Both objects also support LOGICAL functions such as isalpha(), isalphanum(), isupper(), islower() etc.

>>> x=b'Hello' >>> x.isupper() False

Case conversion functions are also allowed.

>>> x=b'Hello' >>> x.upper() b'HELLO'


Discussion

No Comment Found