[Tutor] array module

Dennis Lee Bieber wlfraed at ix.netcom.com
Tue Oct 12 07:24:17 EDT 2021


On Tue, 12 Oct 2021 08:13:09 +0530, Manprit Singh
<manpritsinghece at gmail.com> declaimed the following:

>lst = list(range(100))
>
>import array
>arr = array.array("h", range(100))
>
>sys.getsizeof(lst)
>returns 856
>
>sys.getsizeof(arr)
>returns 268
>
>Shows that the list lst and array arr both are having same data, but there
>is huge difference in size bytes.  so for storing homogenous 1 D data
>arrays are more good ,  Why they are not widely used ?
>What are the specific use cases of this array module ?

	 They work with machine native NUMERIC data types, not Python objects.
Unless you use only the methods documented
https://docs.python.org/3/library/array.html you will require a C-extension
to really take advantage of array.array() -- otherwise you are continuously
converting between Python objects and processor native types. That is, you
will be creating an object header, storage space, copying the native type
into the new object (which includes conversion for short/long etc. to
Python integers, for example); operating on the object, then converting it
back to the array data size, copying the native value into the array, and
disposing of the object header.

	This is one of the problems with just focusing on one aspect of Python
at a time with minimalistic examples.

	Try running some moderately complex arithmetic using values contained
in a list vs the same values contained in an array -- TIMING both. Heck,
even computing squares of integers may be sufficient to show it:

nlst = [x*x for x in olst]

vs

oarr = array.array("suitableCode", olst)
narr = array.array("sameCode", (x*x for x in oarr))	#generator, not list
comprehension, to avoid creating a list only to throw it away

or

oarr = array.array("suitableCode", olst)
narr = array.array("sameCode")
for itm in oarr:
	narr.append(itm*itm)


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list