Sequences and Numpy
Sequences and Numpy
Programmin
g Language
Data structures
• Data structures are a way of organizing and storing data so
that they can be accessed and worked with efficiently.
• Numbers
• Booleans
• Strings
• List
• Tuple
• Set
• Dictionary
Ex:
• list1 = ['physics', 'chemistry', 1997, 2000];
• list2 = [1, 2, 3, 4, 5 ];
• list my_list = []
• my_list = [1, 2, 3]
• my_list = [1, "Hello", 3.4]
• Also, a list can even have another list as an item. This is called nested list.
• my_list = ["mouse", [8, 4, 6], ['a']]
Negative indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second
last item and so on.
Range of Indexes
• You can specify a range of indexes by specifying where to start and where to end the
range.
• When specifying a range, the return value will be a new list with the specified items.
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
Insert Items:
• The insert() method inserts an item at the specified index:
thislist =
["apple", "banana", "cherry"]
thislist.insert(1, "orange") ['apple', 'orange', 'banana', 'cherry']
print(thislist)
T Seshu Chakravarthy Department Of Computer Science and Engineering
Remove List Items
Remove Specified Item:
• The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
['apple', 'cherry']
• If there are more than one item with the specified value, the remove() method removes the first
occurrence:
Remove Specified Index:
• The pop() method removes the element at specified index.
• If you do not specify the index, the pop() method removes the last item.
Program:
numbers = [1, 2, 3, 4, 5, 6, 7]
res=[]
for i in numbers:
res.append(i*i)
print("Input:",numbers)
print("Output:",res) Input: [1, 2, 3, 4, 5, 6, 7]
Output: [1, 4, 9, 16, 25, 36, 49]
extend():it adds all items of a one list to the end of another list.
syntax:
• list1.extend(list2)
• Here, the elements of list2 are added to the end of list1.
vowels = ["C","Python","java","Python"]
count = vowels.count('Python')
print(count) #2 Output:
2
sum() : Calculates sum of all the elements of List.
Syntax: sum(List)
List = [1, 2, 3, 4, 5]
print(sum(List))
T Seshu Chakravarthy Department Of Computer Science and Engineering
Methods Of list
numbers = [1, 3, 4, 2]
strs = ["geeks", "code", "ide", "practice"]
strs.sort()
# Sorting list of Integers in ascending
print(strs)
print(numbers.sort())
print(numbers) # [1, 2, 3, 4]
numbers = [1, 3, 4, 2]
numbers.sort(reverse=True)
print(numbers) # [4, 3, 2,
1]
L=[]
n=int(input("enter size of list"))
i=0
while(i<n):
a=int(input())
L.append(a)
i=i+1
for j in L:
print(j)
list=[5,6,7,8,9]
num=int(input("enter element to search"))
for i in list:
if i==num:
print(num,"found in the list")
break
else:
print(num,"not found in the list")
list=[1,2,4,7,3]
max=list[0]
for a in list:
if a > max:
max = a
print("largets is",max)
• List comprehension is an elegant and concise way to create new list from
an existing list in Python.
• List comprehension consists of an expression followed by for statement
inside square brackets.
pow2 = [2 ** x for x in range(10)]
print(pow2)
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
• n=5
• combinations = [(x,y) for x in range(1,n+1) for y in range(1,n+1)]
• print("All possible combination of pairs from 1 to 5 are:",combinations)
• my_tuple = ()
• my_tuple = (1, 2, 3)
• my_tuple = (1, "Hello", 3.4)
• my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
• my_tuple = 3, 4.6, "dog"
Indexing:
• We can use the index operator [] to access an item in a tuple where the
index starts from 0.
• The index must be an integer, so we cannot use float or other types. This
will result into TypeError
Negative Indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last item and so on.
Slicing
• We can access a range of items in a tuple by using the slicing operator -
colon ":".
print(my_tuple[3])
print(my_tuple[-2])
print(my_tuple[1:3])
print(my_tuple[:])
t=(1,2,3)
t[0] = 5
print(n_tuple[1])
print(n_tuple[0][1])
print(n_tuple[2][2])
T Seshu Chakravarthy Department Of Computer Science and Engineering
Basic tuple Operations
T=(1,5,3,2,5)
print(T. count(5)) # 2
L=[1,5,3]
T=tuple( L )
print(T)
Sorted():
p = ('e', 'a', 'u', 'o', 'i') ['a', 'e', 'i', 'o', 'u’]
['u', 'o', 'i', 'e', 'a']
print(sorted(p))
print(sorted(p,reverse=True))
T Seshu Chakravarthy Department Of Computer Science and Engineering
Even and Odd sum in a tuple
t=(1,2,3,4,5)
sume=0
sumo=0
for i in t:
if(i%2==0):
sume=sume+i
else:
sumo=sumo+i
print(sume)
print(sumo)
for x in thisset:
print(x) cherry
banana
apple
Program:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A.union(B)) #{1, 2, 3, 4, 5, 6, 7, 8}
print(A.intersection(B)) #{4, 5}
print(A.difference(B)) #{1, 2, 3}
print(A.symmetric_difference(B)) # {1, 2, 3, 6, 7, 8}
T Seshu Chakravarthy Department Of Computer Science and Engineering
Python Set Methods
add() : It adds a given element to a set. If the element is already present, it
doesn't add any element.
v = {'a', 'e', 'i', 'u'}
v.add('o')
print('Vowels are:', v)
remove(): method searches for the given element in the set and removes it.
Ex:
language = {'English', 'French', German'}
language.remove('German')
print(language)
Output: {'English', 'French'}
T Seshu Chakravarthy Department Of Computer Science and Engineering
Python Set Methods
numbers = {2.5, 3, 4, -5}
print(sum(numbers)) # 4.5
print(max(numbers)) #4
print(min(numbers))# -5
print(len(numbers)) #4
print (sorted(numbers)) # [-5, 2.5, 3, 4]
• using dict():
my_dict = dict({1:'apple', 2:'ball'})
Ex:
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('apple')
print('The popped element is:', element) #2
clear():
• It is used to remove all the items at once.
squares.clear()
print(squares) # Output: {}
T Seshu Chakravarthy Department Of Computer Science and Engineering
update()
• It is used to update or add elements to dictionary.
• The update() method adds element(s) to the dictionary if the key is not in the dictionary.
• If the key is in the dictionary, it updates the key with the new value.
Ex:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
jersey = {10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'}
print(sorted(jersey))
[5, 10, 18, 45]
print(sorted(jersey. Keys()))
[5, 10, 18, 45]
print(sorted(jersey.values())) ['Dravid', 'Kohli', 'Rohith', 'sachin']
print(len(jersey)) #4
jersey= {10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'}
for x in jersey: sachin
Dravid
print(jersey[x]) Rohith
Kohli
• You can also use the values() method to return values of a dictionary:
sachin
jersey = Dravid
{10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'} Rohith
for x in jersey.values(): Kohli
print(x)
• Loop through both keys and values, by using the items() method:
jersey = {10:'sachin',5:'Dravid',45:'Rohith',18:'Kohli'}
for x,y in jersey.items(): 10 sachin
5 Dravid
print(x,y)
45 Rohith
18 Kohli
d = dict()
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15:
225}
if 'a' in myDict:
del myDict['a']
print(myDict)
• https://www.w3resource.com/python-exercises/dictionary/
Importing NumPy:
import numpy
import numpy as np
print(arr)
print(type(arr))
[1 2 3 4 5]
<class 'numpy.ndarray'>
import numpy as np
print("2x2 Matrix:\n",matrix1)
import numpy as np
A= np.array( [ [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10, 11, 12 ] ] )
print ( "2nd element of 1st row of the matrix = “, A [0] [1] )
print ( "3rd element of 2nd row of the matrix = ", A [1] [2] )
print ( "Second row of the matrix = ",A[1] )
print ( "last element of the last row of the matrix =", A[-1] [-1] )
import numpy as np
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X + Y #np.add(X,Y)
print (“Addition of Two Matrix : \n ", Z)
import numpy as np
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X – Y #np.subtract(X,Y)
print (“Subtraction of Two Matrix : \n ", Z)
• Division operator (/) is used to divide the elements of two matrices element
wise.
import numpy as np
X = np.array ( [ [ 8, 10 ], [ -5, 9 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X / Y #np. Divide(X,Y)
print ("Division of Two Matrix : \n ", Z)
import numpy as np
X = np.array ( [ [ 8, 1 ], [ 5, 2 ] ] )
Y = np.array ( [ [ 2, 6 ], [ 7, 9 ] ] )
Z = X @ Y
print ("dot product of Two Matrix : \n ", Z)
Original Matrix is :
[[8 1]
[5 2]]
Transpose Matrix is :
[[8 5]
[1 2]]
import numpy as np
A = np.array ( [ [ 8, 1 ], [ 5, 2 ] ] )
Original Matrix is :
[[8 1]
[5 2]]
Inverse Matrix is :
[[ 0.18181818 -0.09090909]
[-0.45454545 0.72727273]]
import numpy as np
newarr = arr.reshape(4,3)
print(newarr)
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
for r in result:
print(r)
[12, 4, 3]
[7, 5, 8]
import numpy as np
print("Max is:",np.max(a))
print("Min is:",np.min(a))
print("Average is:",np.mean(a))
print("variance is:",np.var(a))
print("SD is:",np.std(a))
print("After sortng :",np.sort(a))
Max is: 95
Min is: 15
Average is: 55.111111111111114
variance is: 650.9876543209876
SD is: 25.514459710544287
After sortng : [15 25 36 47 58 60 75 85 95]