*Memo:
A bytearray can be enlarged with * and a number as shown below:
v = bytearray(b'ABCDE') * 3
print(v)
# bytearray(b'ABCDEABCDEABCDE')
v = bytearray(b'01234') * 3
print(v)
# bytearray(b'012340123401234')
v = bytearray(b'') * 3
print(v)
# bytearray(b'')
A bytearray and other bytearrays can be concatenated with + as shown below:
v = bytearray(b'ABC') + bytearray(b'DE') + bytearray(b'FGHI')
print(v)
# bytearray(b'ABCDEFGHI')
A bytearray and other bytearrays cannot return:
- all the bytes in them with
'|'(Union: A ∪ B). - their common bytes with
'&'(Intersection: A ∩ B). - the bytes in the bytearray which aren’t in other bytearray with
'-'(Difference: A – B).
v = bytearray(b'AE') | bytearray(b'ACE') | bytearray(b'ABDE')
# TypeError: unsupported operand type(s) for |: 'bytearray' and 'bytearray'
v = bytearray(b'AE') & bytearray(b'ACE') & bytearray(b'ABDE')
# TypeError: unsupported operand type(s) for &: 'bytearray' and 'bytearray'
v = bytearray(b'AE') - bytearray(b'ACE') - bytearray(b'ABDE')
# TypeError: unsupported operand type(s) for -: 'bytearray' and 'bytearray'
A bytearray and other bytearray cannot return the bytes in the bytearray but not in other bytearray or not in the bytearray but in other bytearray with '^' (Symmetric Difference: A Δ B) as shown below:
v = bytearray(b'ABCD') ^ bytearray(b'ACE')
# TypeError: unsupported operand type(s) for ^: 'bytearray' and 'bytearray'
A bytearray can be iterated with a for statement as shown below:
for v in bytearray(b'ABC'):
print(v)
# 65
# 66
# 67
A bytearray can be unpacked with an assignment and for statement, function and * but not with ** as shown below:
v1, v2, v3 = bytearray(b'ABC')
print(v1, v2, v3)
# 65 66 67
v1, *v2, v3 = bytearray(b'ABCDEF')
print(v1, v2, v3) # 65 [66, 67, 68, 69] 70
print(v1, *v2, v3) # 65 66 67 68 69 70
for v1, v2, v3 in [bytearray(b'ABC'), bytearray(b'DEF')]:
print(v1, v2, v3)
# 65 66 67
# 68 69 70
for v1, *v2, v3 in [bytearray(b'ABCDEF'), bytearray(b'GHIJKL')]:
print(v1, v2, v3)
print(v1, *v2, v3)
# 65 [66, 67, 68, 69] 70
# 65 66 67 68 69 70
# 71 [72, 73, 74, 75] 76
# 71 72 73 74 75 76
def func(p1='a', p2='b', p3='c', p4='d', p5='e', p6='f'):
print(p1, p2, p3, p4, p5, p6)
func()
# a b c d e f
func(*bytearray(b'ABCD'), *bytearray(b'EF'))
# 65 66 67 68 69 70
def func(p1='a', p2='b', *args):
print(p1, p2, args)
print(p1, p2, *args)
print(p1, p2, [0, 1, *args, 2, 3])
func()
# a b ()
# a b
# a b [0, 1, 2, 3]
func(*bytearray(b'ABCD'), *bytearray(b'EF'))
# 65 66 (67, 68, 69, 70)
# 65 66 67 68 69 70
# 65 66 [0, 1, 67, 68, 69, 70, 2, 3]
print(*bytearray(b'ABCD'), *bytearray(b'EF'))
# 65 66 67 68 69 70
print([*bytearray(b'ABCD'), *bytearray(b'EF')])
# [65, 66, 67, 68, 69, 70]
Be careful, a huge bytearray gets MemoryError as shown below:
v = bytearray(b'ABCDE') * 1000000000
print(v)
# MemoryError
