![]() ![]() The end result is that the python list is fastest for these operations. With regard to performance, here are some numbers comparing python lists, arrays and numpy arrays (all with Python 3.7 on a 2017 Macbook Pro). TL DR I'd only use an array if you had an exceptional optimization need or you need to interface with C code (and can't use pyrex). So if you plan on adding items, a list is the way to go. This means that appending items to lists is faster. ![]() On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. GvR has an optimization anecdote in which the array module comes out to be the winner (long read, but worth it). If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory. To give you a more direct answer to your question about performance:Īrrays are more efficient than lists for some uses. Most of the time, the array module is used to interface with C code. The array module is kind of one of those things that you probably don't have a need for if you don't know why you would use it (and take note that I'm not trying to say that in a condescending manner!). To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math. However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays. However, Python 2.6+ and 3.x offer a mutable byte string as bytearray. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).Īrray.array is also a reasonable way to represent a mutable string in Python 2.x ( array('B', bytes)). ![]() It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. The array.array type, on the other hand, is just a thin wrapper on C arrays. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |