Basic Python

bytes VS bytearray

Naranjito 2023. 10. 30. 11:42

The bytes and bytearray classes both feature arrays of bytes with values ranging from 0 to 255 for each byte. The main difference is that a bytes object is immutable, which means that once formed, its elements cannot be changed. A bytearray object, on the other hand, allows you to change its elements.

 

  • bytearray

It returns a bytearray object which is an array of the given bytes.

 

- convert list to bytearray

prime_nums=[1,2,3,4]
byte_array=bytearray(prime_nums)
byte_array

>>>
bytearray(b'\x01\x02\x03\x04')

 

- string with encoding 'utf-8'

string='naranja'
arr=bytearray(string, 'utf-8')
arr

>>>
bytearray(b'naranja')

 

- Array of bytes of given integer size

size=5
arr=bytearray(size)
arr

>>>
bytearray(b'\x00\x00\x00\x00\x00')

 

  • The difference between bytes and bytearray

- bytearray : the element is mutable

ord : It must use the 'ord' to put the ASCII code of the character if you want to put a character in an element of the bytearray.

x=bytearray(b'hello')

x[0]
>>>
104

#change the first element
x[0]=ord('a')
x
>>>
bytearray(b'aello')

x[0]
>>>
97

 

- bytes : the element is immutable

y=bytes(b'hello')
y[0]=ord('a')
y[0]
>>>
TypeError: 'bytes' object does not support item assignment

https://dojang.io/mod/page/view.php?id=2462

https://www.programiz.com/python-programming/methods/built-in/bytearray

'Basic Python' 카테고리의 다른 글

abspath, chdir, basename, os.path.join  (0) 2023.11.07
glob  (0) 2023.11.04
pickle, dump, load  (0) 2023.10.24
sys.path, getcwd  (0) 2023.10.19
assert  (0) 2022.12.05