Class XI IP - Python List Dictionary NumpyArrays
Class XI IP - Python List Dictionary NumpyArrays
Variable
e.g a=10, name="BVM", amount=2345.90
Position index always starts with 0 (from left to right or from first value onward)
TUPLE a = ( 23,"45",-6,890,4.5 ) read only collection i.e. oncce created values cannot be changed
LIST a= [ 23,"45",-6,890,4.5 ] heterogeneous collection wherein values can be changed or deleted
ARRAY a= [ 23,45,-6,890,4 ] homogenous collection wherein values can be changed or deleted
numpy is an external package or software that we import into python software so that we can create and
manage arrays.
67 -4 0 52 16 int+float+string
mutable
Python LIST
To create a list by assigning values to a list
Only sequences such as string, tuple, set, dictionary, another list can be assigned to a list.
Numbers (int and float) are not sequences so they can't be assigned to a list lst but can be assigned to a list element lst[i].
mylist=[] print(mylist)#[]
mylist=[1,2,3,4,-2,9,7,0] print(mylist)#[1,2,3,4,-2,9,7,0]
mylist=['a','b','c','d','x','m','r','z'] print(mylist)#['a','b','c','d','x','m','r','z']
mylist=['bvm','ntl','hld','ddn'] print(mylist)#['bvm','ntl','hld','ddn']
mylist=[3.5,6.98,-47.89,0.8,2.33, 2.003] print(mylist)#[3.5,6.98,-47.89,0.8,2.33, 2.003]
mylist=[1,2,'a','b','bvm','ntl',3.5,6.98] print(mylist)#[1,2,'a','b','bvm','ntl',3.5,6.98]
770943221.docx 1
mylist.extend(67) print(mylist)#error - 'int' object is not
iterable
mylist.extend('67') print(mylist)#[12,'3','4','6','7']
mylist.extend([67,89]) print(mylist)#[12,'3','4','6','7',67,89]
mylist.extend((0,1)) print(mylist)#[12,'3','4','6','7',8,9,0,1]
mylist.insert(2,-58) print(mylist)#[12,'3',-58,'4','6','7',8,9,0,1]
mylist=[0,1,2,3,4,5,6,7,8,9]
print(mylist) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(mylist[0]) # 0
print(mylist[-1]) # 9
print(mylist[2:]) #[2, 3, 4, 5, 6, 7, 8, 9]
print(mylist[:2]) #[0, 1]
print(mylist[2:5]) #[2, 3, 4]
print(mylist[2:8:2]) #[2, 4, 6]
print(mylist[::2]) #[0, 2, 4, 6, 8]
print(mylist[::-1]) #[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] reverse list
print(mylist[:-5:-1]) #[9, 8, 7, 6]
print(mylist[0:-5:-1]) #[]
print(mylist[-2:-8:-2]) #[8, 6, 4]
print(mylist[2:-5]) #[2, 3, 4]
print(mylist[-2:-5]) #[]
print(mylist[-2:5]) #[]
770943221.docx 2
mylist=[0,1,2,3,4,5,6,7,8,9]
print(mylist) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
del l print(mylist)mylist=[0,1,2,3,4,5,6,7,8,9] #print(mylist) gives error after
del l;
list already removed completely
del mylist[2] print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #[0, 1,
3, 4, 5, 6, 7, 8, 9]
del mylist[0:2] print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #[2, 3,
4, 5, 6, 7, 8, 9]
del mylist[-5:-2] print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] # [0, 1,
2, 3, 4, 8, 9]
del l [-2:-5] print(mylist)mylist=[0,1,2,3,4,5,6,7,8,9] #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nothing deleted; invalid slice
print(mylist.pop()) mylist=[0,1,2,3,4,5,6,7,8,9]
#9;actually printed all elements till 9
print(mylist.pop(2)) mylist=[0,1,2,3,4,5,6,7,8,9]
#deletes and prints 2
print(mylist.pop(-2)) mylist=[0,1,2,3,4,5,6,7,8,9] #deletes and prints 8
mylist.remove(3) print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #[0, 1,
2, 4, 5, 6, 7, 8, 9]
removes value 3 not the index 3 element
mylist=['a','b','c','d']
mylist.remove('b') print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #['a',
'c', 'd']
770943221.docx 3
Python DICTIONARY
Unordered collection of item where each item consists of a key and a value.
Values are mutable but keys are immutable.
Key:Value pairs can be in the form of a tuple, list or dictionary wherein items are separated by commas. Keys can't
be specified in the form of a list or dictionary as they are mutable sequences. Values can be any mutable or
immutable literals or sequences.
Keys must be unique.
Nested dictionary
student={218120:{'name':'abcd','age':16,'marks':87},216415:{'name':'xyz','age':14,'marks':56}}
for i in student:
print(i,'=',student[i])
218120 = {'name': 'abcd', 'age': 16, 'marks': 87}
216415 = {'name': 'xyz', 'age': 14, 'marks': 56}
770943221.docx 4
Accessing dictionary items
d={'v1':'a','v2':'e','v3':'i','v4':'o'}
print(d.keys()) # dict_keys(['v1', 'v2', 'v3', 'v4'])
print(d.values()) # dict_values(['a', 'e', 'i', 'o'])
for i in d:
print(i, end='..') # v1..v2..v3..v4..; keys
print()
for i in d:
print(d[i], end='..') # a..e..i..o..; values
d={5:'Number','a':'String',(1,2):'tuple'}
print(d) # {5:'Number','a':'String',(1,2):'tuple'}
print(d[5]) # Number
print(d['a']) # String
print(d[(1,2)]) # tuple; here key is a tuple
770943221.docx 5
Numpy
A python package that provides array or ndarray or n-dimensional array object to store multiple homogeneous
items i.e. items of the same data type. Data type of an array is called its dtype.
Used for scientific computing, data analysis and data manipulation in python.
Other packages for data analysis such as pandas, scikit-learn are built on top of Numpy.
Vectorized operation can be performed on an array – if a function is applied, it is performed on every item in the
array, rather than on the array object as a whole.
e.g.
arr+2
will add 2 to each elements of the array arr whereas
lst[2]+2
will give an error rather than adding 2 to all list items.
Size of array is immutable.
An equivalent numpy array occupies much less space than a python list of lists.
770943221.docx 6
a = np.random.rand(4) #1d array of 4 random values
#uniform distribution in [0, 1] with mean 0.5
#array([0.66499843, 0.21296694, 0.30400306, 0.03615942])
b = np.random.randn(4) #1d array of 4 random values
#Gaussian distribution in [-inf, +inf] with mean 0 and std. dev 1
#array([-0.40164684, -0.17132923, -0.88559613, 1.27168109])
np.random.seed(1234) #Setting the random seed
a=np.random.randint(2, size=10)
#array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
a=np.random.randint(1, size=10)
#array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
770943221.docx 7
Numpy array Functions and Methods
import numpy as np
mylist=[[1,2],[3,4],[5,6]]
arr2d=np.array(mylist) print(arr2d) # [[1 2]
[3 4]
[5 6]]
print(arr2d.mean()) #3.5
print(arr2d.max()) #6
print(arr2d.min()) #1
print(np.amin(arr2d, axis=0)) #[1 2]; column-wise min values in the array
print(np.amax(arr2d, axis=1)) #[2 4 6]; row-wise max values in the array
print(np.cumsum(arr2d)) #[1 3 6 10 15 21]; cumulative sum
arr=arr2d.reshape(2,3) print(arr) # [ [1 2 3]
[4 5 6]]
#new shape must accommodate all elements of the array
arr=arr2d.flatten() #create a 1D array from 2D array
#it creates a shallow copy of the original array i.e.
#change in flattened array does not change parent array
print(arr) #[1 2 3 4 5 6]
arr[0]=100 print(arr) #[100 2 3 4 5 6]
print(arr2d)#[[1 2][3 4][5 6]]#no change in parent array
arr=arr2d.ravel() #create a 1D array from 2D array
#but as a reference i.e.
#change in raveled array changes the parent array
arr[0]=100 print(arr) #[100 2 3 4 5 6]
print(arr2d) #[[100 2][3 4][5 6]] #change in parent array
Array Slicing
import numpy as np
mylist=[[1,2],[3,4],[5,6]]
arr2d=np.array(l , dtype='float')
print(arr2d) #[[1. 2.] [3. 4.] [5. 6.]]
print(arr2d[:2,:2]) #prints first 2 rows and first 2 columns
#[[1. 2.] [3. 4.]]
arr = arr2d > 4 #returns an array of index and boolean values?
print(arr) #[[False False] [False False] [ True True]]
print(arr2d[arr]) #[5. 6.]
print(arr2d[::-1]) #reverse the rows of the array
#[[5. 6.] [3. 4.] [1. 2.]]
print(arr2d[::-1, ::-1]) #reverse the whole array – reverse rows and columns both
#[[6. 5.] [4. 3.] [2. 1.]]
arr2d[1,1]=np.nan #replace [1,1] element with nan value
arr2d[2,1]=np.inf #replace [2,1] element with inf value
naninfindex=np.isnan(arr2d)|np.isinf(arr2d)
#get the indexes of nan or inf values
arr2d[naninfindex]=-1 #replace nan and inf values in the array with -1
print(arr2d) #[[ 1. 2.] [ 3. -1.] [ 5. -1.]]
print('Last element from 2nd dim: ', arr2d[1, -1])
#Last element from 2nd dim: 4.0
Accessing array Elelments by Value
mylist=[[1,2,3],[4,5,6],[7,8,9]]
a=np.array(mylist)
770943221.docx 8
#[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
np.where(a==4) #returns the index of an element
#(array([1], dtype=int64), array([0], dtype=int64))
b=np.where(arr==4) #flattens the parent array and then returns index of the value
print(b) #(array([3], dtype=int64),)
a=np.array([1,2,3,4,5,6,7,8]) #[1, 2, 3, 4, 5, 6, 7, 8]
b=np.where((a>2)&(a<4)) #(array([2], dtype=int64),) #returns index of the given value
b=np.where((a>2)&(a<5)) #(array([2, 3], dtype=int64),) #returns index of given values
770943221.docx 9
Delete Numpy Array Eelements
numpy.delete(arr, obj, axis=None)
where,
arr Numpy array
obj index position or list of index positions to be deleted from numpy array arr
axis the axis along which to delete; axis=1 deletes columns, axis=0 deletes rows, axis=None deletes flattened array.
arr=np.array([4,5,6,7,8,9,10,11]) #create a Numpy array from list of numbers
arr = np.delete(arr, 2) #delete element at index position 2
[4 5 7 8 9 10 11]
arr = np.delete(arr, [1,2,3]) #delete element at index positions 1,2 and 3
[4 8 9 10 11]
arr2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]]) #create a 2D array
print(arr2D) # [[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
770943221.docx 10
[0,1,1,2,4,1,6,1,2,9]
mean = sum/10
median
[0,1,1,1,1,2,2,4,6,9]
mode=1
9 for sample
770943221.docx 11