Python Arrays using Array module
kodingwindow@kw:~$ python3 ... >>> from array import * >>> arr = array("s", ["", "", ""])Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d) >>> arr = array("i", [40, 96, 24, 55, 78, -111]) >>> arr array('i', [40, 96, 24, 55, 78, -111]) >>> arr[0] 40 >>> len(arr) 6 >>> max(arr) 96 >>> min(arr) -111 >>> arr.itemsize# memory size of an element stored in the array 4 >>> arr.typecode 'i'
>>> for i in arr: ... print(i) ... 40 96 24 55 78 -111
>>> arr = array("u", ['x', 'y', 'z']) >>> arr array('u', 'xyz') >>> arr[0] 'x' >>> for ch in arr: ... print(ch) ... x y z
Python Array Methods
>>> arr1 = array("i", [40, 96, 24, 55, 78, -111]) >>> arr2 = array("d", [3.14, 9.84]) >>> arr1 array('i', [40, 96, 24, 55, 78, -111]) >>> arr1.append(-111) >>> arr1 array('i', [40, 96, 24, 55, 78, -111, -111]) >>> arr1.count(-111) 2 >>> arr1.extend(arr2)Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only extend with array of same kind >>> arr2 = array("i", [314, 984]) >>> arr1.extend(arr2) >>> arr1 array('i', [40, 96, 24, 55, 78, -111, -111, 314, 984]) >>> arr1.index(-111) 5 >>> arr2.insert(0, 169) >>> arr2 array('i', [169, 314, 984]) >>> arr2.reverse() >>> arr2 array('i', [984, 314, 169]) >>> arr2.pop() 169 >>> arr2.pop(0) 984 >>> arr2 array('i', [314]) >>> arr1 array('i', [40, 96, 24, 55, 78, -111, -111, 314, 984]) >>> arr1.remove(-111) >>> arr1 array('i', [40, 96, 24, 55, 78, -111, 314, 984]) >>> arr1.tolist() [40, 96, 24, 55, 78, -111, 314, 984]
What Next?
Python indexing and slicing on an array
Python NumPy Arrays
Python to create a view() and copy() of NumPy arrays
Advertisement