You are on page 1of 27

VELAMMAL ENGINEERING COLLEGE

Department of Computer Science and Engineering


19CS103T /Programming for Problem Solving using Python
19CS105T/Python Programming

UNIT-III STRINGS and LISTS

Strings-String slices, immutability, string methods and operations


-Lists-creating lists, list operations, list methods, mutability,
aliasing, cloning lists, list traversal, list processing-
list comprehension. Illustrative programs: String palindrome,
linear search, binary search.

1. Strings:
❖ String is a sequence which is made up of one or more UNICODE
characters.
❖ The character can be a letter,digit, whitespace or any other symbol.
❖ Python has a built-in string class named "str" that has many useful
features.
❖ A string can be created by enclosing one or more characters in
single,double or triple quote.
❖ To declare and define a string by creating a variable of string type:
>>> name = "India"
>>> graduate = 'N’
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!'''
>>>country = name nationality = str("Indian")

2. Accessing Characters in a String - Index


❖ Individual characters in a string are accessed using the subscript ([ ])
operator. The expression in brackets is called an index.
❖ The index specifies a member of an ordered set and in this case it
specifies the character to be accessed from the given set of characters in
the string.

`
>>> str = "Hello World!"
>>> str[3]
>>> l

❖ The index of the first character is 0 and that of the last character is n-1
where n is the length of the string.
❖ The index must be an integer (positive, zero or negative).
❖ Negative indices are used when the characters of the string are accessed
from right to left.
❖ Starting from right hand side, the first character has the index as -1 and
the last character has the index –n where n is the length of the string.
>>> str[-3]
>>> r
❖ The index can also be an expression including variables and operators but
the expression must evaluate to an integer.

>>> str = "Hello World!"


>>> str[2+4]
>>> W
❖ If index bound exceeded (below 0 or above n-1), then an IndexError is
raised.

3. String slices:
➢ A substring of a string is called a slice. The slice operation is used to
refer to sub-parts of sequences and strings within the objects.
➢ Slicing operator [ ] is used to access subset of string from original string
➢ Syntax :
string_var [START INDEX : END INDEX: STEP]

Ex. str[n : m : k] returns every kth character extracted from


the string starting from index n (inclusive) and ending at m (exclusive).
By default, the step size is one
>>> str1= "Hello World!"
>>> str1[7:10]
>>> 'orl'
>>> str1[0:10:2]

`
>>>'HloWr'
>>> str1[0:10:3]
>>>'HlWl'

Note :
1. The numbers of characters in the substring will always be equal to
m-n
>>> str1= "Hello World!"
#index that is too big is truncated down to
#the end of the string
>>> str1[3:20]
>>> 'lo World!'

2. If the first index is not mentioned, the slice starts from index 0.
>>> str1[:5]
>>> 'Hello'
3. If the second index is not mentioned, the slicing is done till the
length of the string.
>>> str1[6:]
>>>'World!'
4. Negative indexes can also be used for slicing.
>>> str1[-6:-1]
>>> 'World'

4. Traversing a String:
To access each character of a string or traverse a string, for loop and while
loop are used
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')
>>> Hello World! #output of for loop
➢ for loop starts from the first character of the string str1 and
automatically ends when the last character is accessed.

(B) String Traversal Using while Loop:


>>> str1 = 'Hello World!'
>>> index = 0
>>> while index < len(str1):
print(str1[index],end = '')
index += 1
>>> Hello World! #output of while loop
➢ while loop runs till the condition index< len(str) is True, where index
varies from 0 to len(str1) -1.

`
5. Immutability:
➢ A string is an immutable data type.
➢ The contents of the string cannot be changed in-place after it
has been created. An attempt to do this would lead to an error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support item
assignment

6. String Operations and Functions:


i. Concatenation : Python allows to join two strings using
concatenation operator plus which is denoted by symbol +.
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
>>> 'HelloWorld!'
ii. Repetition: Python allows to repeat the given string using
repetition operator which is denoted by symbol *.
#assign string 'Hello' to str1
>>> str1 = 'Hello'
#repeat the value of str1 2 times
>>> str1 * 2
>>>'HelloHello'

iii. Membership : Python has two membership operators 'in' and 'not
in'. The 'in' operator takes two strings and returns True if the first
string appears as a substring in the second string, otherwise it
returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
>>> True
>>> 'My' in str1
>>> False
The 'not in' operator also takes two strings and returns True if the
first string does not appear as a substring in the second string,
otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
>>> True
>>> 'Hello' not in str1
>>> False

`
iv. Comparing strings: Two strings can be compared using relational
operators which return True or False

v. len():This function returns the length of the string.


Ex:>>>t=”Welcome”
>>> len(t)
5
vi. max( ) : This function returns the maximum alphabetical character
from the string
vii. min( ) : This function returns the minimum alphabetical character
from the string
Ex: >>> max(t)
'o'
>>> min(t)
'e'
viii. ord( ) : This function returns the ASCII code of the
character
ix. chr( ) : This function returns character represented by a ASCII
number.

x. sorted():This function returns sorted string as list .


Ex: >>> sorted(t)
['e', 'h', 'l', 'l', 'o']

`
7. String Methods:

1. str.lower ( ) : Return a string with all the cased characters converted to


lowercase.
>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.lower ( )
' this is string example. . . .wow ! ! ! '

2. str.upper ( ): Return a string with all the cased characters converted to


uppercase.
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.upper ( )
' THIS IS STRING EXAMPLE. . . . WOW ! ! ! '

3. str.istitle ( ) : Return True, if the string is title cased, otherwise False is


returned.
>>> str=" This Is String Example. . .Wow ! ! ! "
>>> str . istitle ( )
True

4. str.capitalize ( ) : Return a string with its first character capitalized and


the rest lowercase.
>>> str=" this Is stRing example ....... wow ! ! ! "
>>> str.capitalize ( )
' This is string example.......wow ! ! !

5. str.title ( ) : Return a title cased version of the string, where words start
with an uppercase character and the remaining characters are lowercase.
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.title ( )
' This Is String Example. . . .wow ! !

6. str.swapcase ( ) : Return a copy of the string with reversed character


case.
>>> str='' This is string example. . . .WOW ! ! ! "
>>> str . swapcase ( )
' tHIS IS STRING EXAMPLE. . . .wow ! ! ! '

7. str.isalnum( ) : Return true if all characters in the string are


alphanumeric, false otherwise.

`
>>> str=" this2009 ”
>>> str.isalnum ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalnum( )
False

8. str. isalpha ( ) : Return true if all characters in the string are


alphabetic, false otherwise.

>>> str=" this "


>>> str.isalpha ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalpha ( )
False

9. str.isdigit( ) : Return True, if all characters in the string are digits,


otherwise False is returned.
>>> str="this2009"
>>> str.isdigit ( )
False
>>> str=" 2009 "
>>> str.isdigit ( )
True

10. str . isspace ( ) : Return True, if there are only whitespace characters in
the string, otherwise False is returned.
>>> str= " "
>>> str.isspace ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.isspace ( )
False

11. str.islower ( ) : Return True, if all cased characters in the string are in
lowercase, false otherwise.
>>> str=" THIS is string example. . . .wow! ! ! "
>>> str.islower( )
False
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.islower ( )
True

12. str.isupper ( ) : Return True, if all cased characters in the string are
uppercase, otherwise False isreturned.

`
>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.isupper ( )
True
>>> str=" THIS is string example. . . .wow ! ! ! "
>>> str.isupper ( )
False

13. str.count(sub[,start[, end]]) : Return the number of non-overlapping


occurrences of sub-string sub in the range [start, end]. Optional
arguments start and end are interpreted as in slice notation.
>>> str=" this is string example. . . .wow ! ! ! "
>>> sub=" i "
>>> str.count (sub , 4 , 40)
2

14. str.find(sub[,start[,end]]) : Return the lowest index in the string where


the sub-string sub is found, such that sub is contained in the slice s [ start:
end]. Optional arguments start and end are interpreted as in slice notation.
Return -1, if the sub is not found.
>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>>> str1.find ( str2 )
15
>>> str1.find ( str2 , 10 )
15

15. str.index ( sub [ , start [ , end ] ] ) : Return the lowest index in the string
where the sub-string sub is found, such that sub is contained in the slice s
[ start: end] (like find ( ) but raise ValueError when the sub-string is not
found)
>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>.> str1. index ( str2 )
15
>>> str1.index ( str2 , 10 )
15

16. str.rfind(sub[,start[, end]] ) : Return the highest index in the string


where the sub-string sub is found, such that sub is contained within s
[start: end]. Optional arguments start and end are interpreted as in slice
notation. Return -1 on failure.

`
>>> str1=" this is really a string example. . . .wow !
! ! "
>>> str2=" is "
>>> strl.rfind ( str2 )
5
>>> str1.rfind ( str2 , 0 , 10 )
5
17. str. join ( iterable ) : Return a string which is the concatenation of the
strings in the iterable. The separator between elements is the string str
providing this method.
>>> str="-"
>>> seq= ( " a " , " b " , " c " )
>>> str. join ( seq )
' a-b-c '
>>> seq=[ " a " , " b " , " c " ]
>>> str.join (seq)
' a-b-c '

18. str.replace ( old , new [ , count ] ) : Return a string with all occurrences
of substring old replaced by new. If the optional argument count is given,
only the first count occurrences are replaced.
>>> str=" this is string example. . . . wow ! ! ! this
is really string"
>>> str.replace (" is "," was ")
'thwas was string example. . . .wow ! ! ! thwas was
really string’

19. str.center ( width [ , fillchar ] ) : Return centered string of length width.


Padding is done using optional argument fillchar (default is a space).
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.center ( 40 ,' a ' )
' aaaathis is string example. . . .wow ! ! ! aaaa'

20. str.ljust ( width [ , fillchar ] ) : Return the string left-justified in a string


of length width. Padding is done using the optional argument fillchar
(default is a space). The original string is returned if the width is less than
or equal to len(str).
>>> str="this is string example. . . .wow! ! ! "
>>> str . ljust (50, ' 0 ' )
'this is string example. . . .wow ! !
!000000000000000000 '

21. str.rjust ( width [ ,fillchar ] ) : Return the right-justified string of length


width. Padding is done using the optional argument fillchar (default is a
space). The original string is returned if the width is less than or equal to
len(str).

`
>>> str="this is string example. . . .wow ! ! ! "
>>> str.rjust ( 50 , ' 0 ' )
'000000000000000000this is string example. . . .wow ! !
! '

22. str.strip ( [ chars ] ) : Return a string with the leading and trailing
characters removed. The chars argument is a string specifying the set of
characters to be removed. If omitted or None, the chars argument defaults
to removing whitespace.
>>> str=" 0000000this is string example. . . . wow ! ! ! 0000000 "
>>> str.strip ( ' 0 ' )
'this is string example. . . .wow ! ! ! '

23. str.split ( [ sep [ , maxsplit ] ] ) : Return a list of the words from the
string using sep as the delimiter string. If maxsplit is given, at most
maxsplit splits are done (thus, the list will have at most maxsplit + 1
elements). If maxsplit is not specified or -1, then all possible splits are
made. If sep is not specified or None, any whitespace string is a separator.
>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> str . split ( )
['Line1-abcdef', ' Line2-abc ', ' Line4-abcd ' ]
24. str. splitlines ( [ keepends ] ) : Return a list of the lines in the string,
breaking at line boundaries. Line breaks are not included in the resulting
list unless keeping is given.
>>> str="1ine1-a b c d e f\n1ine2- a b c\ n\n1ine4- a b c d "
>>> str.splitlines ( )
[ ' Line1-a b c d e f', ' Line2- a b c ' , ' ' , ' Line4- a b
c d ' ]

9. Lists : List are ordered collections of other objects which are mutable.
It is a sequence in which elements are written as a list of comma-separated
values (items) between square brackets.
The key feature of a list is that it can have elements that belong to different
data types.
Syntax for defining a list
List_variable = [val1, val2,...]
Ex.

l=[1, 'a', 'abc',2.5, (3,4,5)]

10. Creating lists

`
11. Access Values in Lists
List Index : Index operator [ ] to access an item in a list.
Indices start at 0
Ex:
l=[10,20,30,40,50,60,70]
print(l[5])

Output:
60

Slicing List : To access values in lists, square brackets are used to slice
along with the index or indices to get value stored at that index.

The syntax for the slice operation


seq = List[start:stop:step]
Ex:
l=[10,20,30,40,50,60,70]
print(l[3:7])

Output:
[40, 50, 60, 70]

12. Negative indexing of List :


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.
Ex:
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])

Output:
e
p

`
13. Mutability :
The list is a data type that is mutable. Once a list has been created:
➢ Elements can be modified.
➢ Individual values can be replaced.
➢ The order of elements can be changed.
Lists are also dynamic. Elements can be added and deleted from a list,
allowing it to grow or shrink

Ex:
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham',
'lobster']
>>> a[2] = 10
>>> a
['spam', 'egg', 10, 'tomato', 'ham', 'lobster']
>>> a[-1] = 20
>>> a
['spam', 'egg', 10, 'tomato', 'ham', 20]

In the above example element at index 2 is modified in-place.


14. Nested list : It is a list within another list. A list has elements of
different data types which can include even a list.
Ex:
l=[1, 'a', 'abc',[40,50,60,70],2.5]
print(l[3][1])
Output:
50

15. List traversal: To iterate over all the elements in a list the
following methods can be used.
Method #1: Using For loop
list = [1, 3, 5, 7, 9] Output :
for i in list: 1
print(i) 3
5
7
9

Method #2: For loop and range()


list = [1, 3, 5, 7, 9] Output :
length = len(list) 1
for i in range(length): 3
print(list[i]) 5
7
`
9

Method #3: Using while loop


list = [1, 3, 5, 7, 9] Output :
length = len(list) i = 0 1
while i < length: 3
print(list[i]) 5
i += 1 7
9

16. List Operations and Functions


1. Concatenation : Joins two list using ‘ + ‘ operator.
2. Repetition : Repeats elements in the list using ‘*’ operator.
3. in and not in :Checks if the elements is present in the list
4. Comparing lists: Two lists can be compared using relational operators which
return True or False
5. len() : Returns length of the list
6. max ( ) : Returns maximum value in the list
7. min ( ) : Returns minimum value in the list
8. sum ( ) : Adds the values in the list that has numbers and returns the sum
9. all ( ) :Returns True if all elements of the list are true (or if the list is
empty
10. any( ) : Returns True if any element of the list are true. If the list
isempty, returns False
11. list ( ) : Converts an iterable (tuple,string,set,dictionary)to a list
11.sorted ( ) : Returns a new sorted list. The original list is not sorted
Ex :
x = [5, 2, 3]
y = [7, 9, 10]
print("Concatenation of list x and y :", x + y)
print("Repetition of list y :", y *3)

`
print("3 in x :", x + y)
print(x>y, x!=y)
print(len(x))
print("Maximum in list x :", max(x))
print("Minimum in list x :", min(x))
print("Sum of list x :", sum(x))
print("all fn using y :", all(y))
print("any fn using y :", any(y))
print("sorting list x :", sorted(x))
print("Converting string to list :", list("abcd"))

Output :
Concatenation of list x and y : [5, 2, 3, 7, 9, 10]
Repetition of list y : [7, 9, 10, 7, 9, 10, 7, 9, 10]

3 in x : [5, 2, 3, 7, 9, 10]
False True
3
Maximum in list x : 5
Minimum in list x : 2
Sum of list x : 10
all fn using y : True
any fn using y : True
sorting list x : [2, 3, 5]
Converting string to list : ['a', 'b', 'c', 'd']

17. List methods


1. append ( ) : Appends an element to the list.
Syntax : list.append(obj)

`
n=[6,0,1,2,9]
n.append(10)
print(n)
n.append([11,12,13])
print(n)
Output :
[6, 0, 1, 2, 9, 10]
[6, 0, 1, 2, 9, 10, [11, 12, 13]]

2. count ( ) : Count the number of times an element appears in the list


Syntax : list.count(obj)
n=[6,0,1,2,9,3,2,0,3]
print(n.count(3))
Output :
2

3. index ( ) : Returns the lowest index of obj in the list. Gives a Value
Error if obj is not present in the list.
Syntax : list.index(obj)
n=[6,0,1,2,9,3,2,0,3]
print(n.index(9))
print(n.index(10))
Output :
4
Traceback (most recent call last):
File "<string>", line 3, in <module>
ValueError: 10 is not in list

4. insert ( ) : Insert obj at the specified index in the list


Syntax : list.insert(index, obj)

`
n=[6,0,1,2,9]
n.insert(2,50)
print(n)
Output :
[6, 0, 50, 1, 2, 9]

5. pop ( ) : Removes the element in the specified index in the list. If no


index is specified, it removes the last element(obj) in the list.
Syntax : list.pop([index])
n=[6,0,1,2,9]
n.pop(1)
print(n)
n.pop()
print(n)
Output :
[6, 1, 2, 9]
[6, 1, 2]
6. remove ( ) : Removes or deletes obj from the list. Gives a Value
Error if obj is not present in the list.If multiple copies of obj exist in
the list, then the first value is deleted
Syntax : list.remove(obj)
n=[6,0,1,2,9]
n.remove(1)

`
print(n)
n.remove(10)
print(n)
Output :
[6, 0, 2, 9]
Traceback (most recent call last):
File "<string>", line 4, in <module>
ValueError: list.remove(x): x not in list

7. reverse ( ) : Reverses the elements in the list.


Syntax : list.reverse( )
n=[6,0,1,2,9]
n.reverse()
print(n)
Output :
[9, 2, 1, 0, 6]
8. sort ( ) : Sort the elements in the list.
Syntax : list.sort( )
n=[6,0,1,2,9]
n.sort()
print(n)
Output :
[0, 1, 2, 6, 9]
9. extend ( ) : Adds the element in a list to the end of the list.
Syntax : list.extend(list obj)
n=[6,0,1,2,9]
n.extend([11,12,13])
print(n)
Output :
[6, 0, 1, 2, 9, 11, 12, 13]
10. clear ( ) : Removes all the elements from the list
Syntax : list.clear ( )

`
n=[6,0,1,2,9]
n.clear()
print(n)
Output :
[ ]
11. copy ( ) : Returns a copy of the list
Syntax : list.copy ( )
n=[6,0,1,2,9]
a=n.copy()
print(n)
print(a)
Output :
[6, 0, 1, 2, 9]
[6, 0, 1, 2, 9]

18. Aliasing : The process of giving another reference variable to the


existing list is called aliasing.
Ex:
x=[10,20,30,40]
y=x
print(id(x))
print(id(y))

Output:
139985896812096
139985896812096

`
➢ If changes are done in reference variable content, then those changes
will be reflected to the other reference variable.

Ex:
x=[10,20,30,40]
y=x
y[1]=777
print(x)

Output :
[10,777,30,40]

19. Cloning lists: The process of creating exactly duplicate


independent object (list) is called cloning.
(i) Using slicing technique - create a new list and copy every
element using slicing operator
Ex:
x=[10,20,30,40]
y=x[:]
y[1]=777
print(x)
print(y)

Output :
[10,20,30,40]
[10,777,30,40]

`
(ii) Using the list() method- cloning a list by using the built-in
function list( )
Ex:
def Cloning(li1):
li_copy = list(li1)
return li_copy

li1 = [4, 8, 2, 10, 15, 18]


li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)

Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

(iii) Using the copy() method - The inbuilt method copy is used to
copy all the elements from one list to another

Ex:
def Cloning(li1):
li_copy =[]
li_copy = li1.copy()
return li_copy

# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

`
(iv) Using the append() / extend() method - This can be used for
appending and adding elements to list or copying them to a new
list. It is used to add elements to the last position of list.

Ex:
def Cloning(li1):
li_copy =[]
for item in li1:
li_copy.append(item)
return li_copy
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)

Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

20. List processing-list comprehension:


➢ Python's List Comprehension is a quick and compact syntax to generate a
list from a string or any other list.
➢ Used to Create a new list by performing an operation on each item in the
existing list
Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
➢ Comprehension of the list is considerably faster than using the for loop to
process a list.
➢ List comprehensions provide a more concise way to create lists in
situations where map() and filter() and/or nested loops would currently be
used.
Example 1 : To compute the square of each number in a list.
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> squares = [x**2 for x in lst]
>>> print(squares)

`
>>>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Example 2: To find even number list in a range of integers
>>> [i for i in range(10) if i % 2 ==0]
>>>[0, 2, 4, 6, 8]

21. Illustrative programs

1. Write a Python program to find String palindrome


Program:
a=input("Enter a string:")
b=a.lower()
c=b[::-1]
if b==c:
print(a,"is a palindrome")
else:
print(a,"is not a palindrome")

Output:
Enter a string: Radar
Radar is a palindrome

2. Write a Python program to perform linear search using list


Program:
def linear(lst,sval):
for i in range(len(lst)):
if lst[i]==sval:
return(i)
return -1

n=int(input("Enter no. of elements:"))


l=[]
for i in range(n):
val=int(input("enter value:"))
l.append(val)
print(l)
searchval= int(input("enter value to be searched:"))
a=linear(l,searchval)
if a==-1:
print("Element not found")
else:
print("Element found at index",a)

`
Output:
Enter no. of
elements:5enter
value:23
enter
value:45
enter
value:67
enter
value:89
enter
value:100
[23,45,67,89,
100]
enter value to be
searched:67Element found
at index 2

3.Write a Python program to perform binary search using list


Program:
def binsearch(lst,sval):
low,high=0,(len(lst)-1)
while (low<high):
mid=(low+high)//2
if lst[mid]<sval:
low=mid+1
elif lst[mid]>sval:
high=mid-1
else:
return(mid)
return -1
n=int(input("Enter the no of elements in list:"))
l =[]
for i in range(n):
ele=int(input("Enter the list elements:"))
l.append(ele)
x = int(input("Enter the element to search:"))
a=binsearch(l,x)
if a==-1:
print("Element not found")
else:
print("Element found at index",a)
Output:
Enter the no of elements in list:5
Enter the list elements:2
Enter the list elements:3
Enter the list elements:4
Enter the list elements:5
Enter the list elements:6
Enter the element to search:8
Element not found
`
5. Implement python script to
i. Add matrices
ii. Multiply matrices
iii. Find Transpose of a matrix
#i) MATRIX MULTIPLICATION

A=[[1,2,3],
[1,2,3],
[1,2,3]]
B=[[2,3,1],
[2,3,1],
[2,3,1]]
C=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j]+=A[i][k]*B[k][j]
for r in C:
print(r)

Output :
[12, 18, 6]
[12, 18, 6]
[12, 18, 6]

#ii) MATRIX ADDITION

A=[[3,3,3],
[2,2,2],
[1,1,1]]

B=[[1,1,1],
[2,2,2],
[3,3,3]]

C=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
C[i][j]=A[i][j]+B[i][j]
for r in C:
print(r)

Output :
[4, 4, 4]
[4, 4, 4]
[4, 4, 4]

`
#iii) TRANSPOSE OF MATRIX

A=[[1,2,3],
[4,5,6]]
B=[[0,0],
[0,0],
[0,0]]

for i in range(len(A)):
for j in range(len(A[0])):
B[j][i] = A[i][j]
for r in B:
print(r)

Output :
[1, 4]
[2, 5]
[3, 6]

5. Write a Python Program to Remove the Duplicate Items from a List.

Program:
list1=[2,8,4,5]
list2=[4,7,8,9]
list_intersection = list(set(list1) ^ set(list2))
print("Intersection of {} and {} is : {}".format(
list1, list2, list_intersection))

Output:
Intersection of [2, 8, 4, 5] and [4, 7, 8, 9] is : [2, 5, 7, 9]

6. Write a function called is_anagram that takes two strings and returns True if they are anagrams.

Program:

def is_anagram(s1,s2):
s1=sorted(s1)
s2=sorted(s2)
if(s1==s2):
return True
else:
return False

a=input("enter 1st string:")


b=input("enter 2nd string:")
print("Is Anagram:",is_anagram(a.lower(),b.lower()))

Output:
enter 1st string:Ajax
enter 2nd string:Jaxa

`
Is Anagram: True

7. Write a function deleteChar() which takes two parameters one is a string and other is a
character. The function should create a new string after deleting all occurrences of the character
from the string and return the new string.
Program:
def delchar(string,char):
str=" "
for i in string:
if i==char:
str=string.replace(i, '')
return str
a=input("enter string:")
b=input("enter char to be deleted:")
print("the string:", delchar(a, b))

Output :
enter string:abcdxyzd
enter char to be deleted:d
the string: abcxyz

8. Write a Python program to count Uppercase, Lowercase, special character and numeric
values in a given string.

Programs:
v='Shop open@3pm'
s=v.replace(" ","")
a=0
b=0
c=0
d=0
for i in s:
if i.isdigit()==True:
a+=1
elif i.isupper()==True:
b+=1
elif i.islower()==True:
c+=1
else:
d+=1
print('digit values:',a)
print('uppercase letters:',b)
print('lower case letters:',c)
print('special char:',d)

Output:
digit values: 1
`
uppercase letters: 1
lower case letters: 9
special charc: 1

9.Count no. of vowels and consonants in string


Program:
str=input("Enter string:")

str1="".join(str.split())
vowel="aeiou"
vcount=0
ccount=0

for i in str1:
if i.lower() in vowel:
vcount+=1
else:
ccount+=1
print("No. of vowels in string ",str ,vcount)
print("No. of consonents in string ",str ,ccount)

Output
Enter string:python program
No. of vowels in string python program 3
No. of consonents in string python program 10

You might also like