Array in Python
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= [Link](“i”, [1,2,3,4])
Or
Import array as arr
a = [Link](“i”, [1,2,3,4])
Or
From array import *
a = [Link](“i”, [1,2,3,4])
Array Methods
[Link]() Method
Like the sequence types, the array class also supports the reverse()
method which rearranges the elements in reverse order.
[Link]() Method
The count() method returns the number of times a given element occurs in the
array.
[Link]()
The index() method in array class finds the position of first occurrence of a given
element in the array.
[Link]()
The fromlist() method appends items from a Python list to the array object.
[Link]()
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 "[Link]" will be created in the current
directory.
[Link]()
The fromfile() method reads a binary file and appends specified number of items
to the array object.
(rb) Read and
binary
Other methods
[Link](x) : add element x at the end of the array
[Link](x) : append x at the end of the array. X can be be another array or
iterable object
[Link](i,x) insert x at position i
[Link](x) :remove item ‘x’ from array and return it
[Link]() : remove lat element from array
[Link](x) : remove the first occurrence of x in the array
two-dimensional array
Use array method of numpy
print("\n")
arr2 = [Link]([[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 = [Link]() creates mirror images of
array called shallow copy. When one changes other also
copy() : if “a” and “b” are two array then b = [Link]() 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
Size : gives total number of elements in array
Dtype : gives datatype of elements in an array
Reshape () : used to change row to column and column to row
flatten() : collapse multidimensional array into one dimension
End