I recently came across the dataType called bytearray in python. Could someone provide scenarios where bytearrays are required?
I recently came across the dataType called bytearray in python. Could someone provide scenarios
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A
bytearrayis very similar to a regular python string (strin python2.x,bytesin python3) but with an important difference, whereas strings are immutable,bytearrays are mutable, a bit like alistof single character strings.This is useful because some applications use byte sequences in ways that perform poorly with immutable strings. When you are making lots of little changes in the middle of large chunks of memory, as in a database engine, or image library, strings perform quite poorly; since you have to make a copy of the whole (possibly large) string.
bytearrays have the advantage of making it possible to make that kind of change without making a copy of the memory first.But this particular case is actually more the exception, rather than the rule. Most uses involve comparing strings, or string formatting. For the latter, there’s usually a copy anyway, so a mutable type would offer no advantage, and for the former, since immutable strings cannot change, you can calculate a
hashof the string and compare that as a shortcut to comparing each byte in order, which is almost always a big win; and so it’s the immutable type (strorbytes) that is the default; andbytearrayis the exception when you need it’s special features.