What is the reason of having two ways of extending a bytearray?
- An operator is not chainable like function calls, whereas a method is.
- The
+=
operator cannot be used with nonlocal variables.
- The
+=
is slightly faster
.extend()
may/might/could sometimes possibly be more readable
Are they performing exactly the same task?
Depends on how you look at it. The implementation is not the same, but the result usually is. For a bunch of examples and explanations, maybe try the SO search, and for example this question: Concatenating two lists - difference between '+=' and extend()
Which one should be used when?
If you care about the small performance difference, use the operator when you can. Other than that, just use whichever you like to look at, of course given the restrictions I mentioned above.
But the main question is why += and .extend do not share the same internal function to do the actual work of extending a bytearray.
Because one is faster but has limitations, so we need the other for the cases where we do have the limitations.
Bonus:
The increment operator might cause some funny business with tuples:
if you put a list in a tuple and use the += operator to extend the list, the increment succeeds and you get a TypeError
Source: https://emptysqua.re/blog/python-increment-is-weird-part-ii/