Array in Python-4
Array in Python-4
Array
syntax
Arrayname = array(typecode, [ n1,n2.,n3, elements]
Typecode
b= signed integer 1 byte
B= unsigned integer 1 byte
i= signed integer 2 byte
I= unsigned integer 2 byte
l= signed integer 4 byte
L= unsigned integer 4 byte
f= Floating point 4 byte
d= double precision floating point 8 byte
u= unicode integer 2 byte
Creating array (three ways)
Import array module
a= array.array(“i”, [1,2,3,4])
Or
Import array as arr
a = arr.array(“i”, [1,2,3,4])
Or
From array import *
a = arr.array(“i”, [1,2,3,4])
Array Methods
array.reverse() Method
Like the sequence types, the array class also supports the reverse()
method which rearranges the elements in reverse order.
array.count() Method
The count() method returns the number of times a given element occurs in the
array.
Array.index()
The index() method in array class finds the position of first occurrence of a given
element in the array.
Array.fromList()
The fromlist() method appends items from a Python list to the array object.
Array.tofile()
The tofile() method in array class writes all items in the array to the file object f.
After running the above code, a file named as "list.txt" will be created in the current
directory.
Array.fromfile()
The fromfile() method reads a binary file and appends specified number of items
to the array object.
print("\n")
arr2 = np.array([[1,2,3,4], [5,6,7,8]])
print(arr2)
print(type(arr2))
Multidimensional array
Multidimensional array
Multidimensional array
array
Aliasing array : if “a” and “b” are two arrays then a = b means both pointing to
same array. When one changes other also
view() : if “a” and “b” are two array then b = a.view() creates mirror images of
array called shallow copy. When one changes other also
copy() : if “a” and “b” are two array then b = a.copy() creates copy of array where
both array are independent. When one changes other do not. This is called deep
copy.
Attributes of array
ndim: represents number of dimensions or axes.
shape() : displays number of elements in one dimension array or display row and
column in two dimension array