2

Assigning a bytearray to another variable seems to simply assign the address to the bytearray and does not really create a copy. Here is a sample code:

a = bytearray(b'000000000000000011111111')
b = a
print ('a =', a)
print('b =', b)
a[0] = ord('1')
print ('a =', a)
print ('b =', b)

with the following output:

a = bytearray(b'000000000000000011111111')
b = bytearray(b'000000000000000011111111')
a = bytearray(b'100000000000000011111111')
b = bytearray(b'100000000000000011111111')

So, when variable a is modified, b gets implicitly modified too. How to copy the contents of variable a to another variable?

Tania
  • 418
  • 3
  • 20
  • 1
    Generic version of this question: [How can I create a copy of an object in Python?](https://stackoverflow.com/q/4794244/4518341) The accepted answer doesn't really apply to a bytearray, but [Aaron Hall's answer](https://stackoverflow.com/a/46939443/4518341) does. – wjandrea Jan 17 '21 at 18:29

1 Answers1

4

Use bytearray.copy method:

b = a.copy()

Slicing will also create a copy:

b = a[:]
wim
  • 338,267
  • 99
  • 616
  • 750