There is a table in the docs that outlines the basic operations on sequence types.
In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example,
bytearray
only accepts integers that meet the value restriction0 <= x <= 255
).
We turn our attention to the row on .extend()
:
s.extend(t) or s += t |
extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t ) |
Now, s.extend(t)
and s += t
are not necessarily literally the same, but they should do roughly the same thing: modify s by putting all the things in t at the end.
However, we run into a discrepancy:
test = bytearray([1, 2, 3])
test.extend([1, 2, 3])
print(test)
>>> bytearray(b'\x01\x02\x03\x01\x02\x03')
test = bytearray([1, 2, 3])
test += [1, 2, 3]
print(test)
>>> TypeError: can't concat list to bytearray
This error is raised in every version of Python I could check (at least as far back as 2.7), so I presume the behavior is “intended”. Thus, I would suggest updating the docs to reflect this.
But, given what the docs do say, this behavior seems definitely not intended. Not only should .extend
and +=
do essentially the same thing, each item in [1, 2, 3]
is an acceptable member of a bytearray
, which the leading paragraph very clearly delineates as acceptable!
I’d be interested if there’s any “deliberate” reason for this TypeError
that someone could provide or if its just a holdover from Python 2. Whatever the case, something should be updated, with the docs being the easier option but the behavior IMO needing attention regardless.