Chapter 8,9,10 Notes
Chapter 8,9,10 Notes
STRINGIN
PYTHON
6.1 Introduction:
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String:
Strings are immutable in python. It means it is unchangeable. At the same memory
address, the new value cannot be stored.
Each character has its index or can be accessed using its index.
String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3,............in the backward direction.)
Example:
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1
The index of string in forward direction starts from 0 and in backward direction starts from
-1.
The size of string is total number of characters present in the string. (If there are n
characters in the string, then last index in forward direction would be n-1 and last index
in backward direction would be –n.)
Page
1
print(ch, end= ‘ ‘)
Page
2
Output:
kendriya
i. String concatenation Operator: The + operator creates a new string by joining the
two operand strings.
Example:
>>>”Hello”+”Python”
‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’
Page
3
ii. String repetition Operator: It is also known as String replication operator. It
requires two types of operands- a string and an integer number.
Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’
b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise False
not in - Returns True if a character or a substring does not exist in the given string; otherwise False
Example:
>>> "ken" in "Kendriya
Vidyalaya" False
>>> "Ken" in "Kendriya
Vidyalaya" True
>>>"ya V" in "Kendriya Vidyalaya"
True
>>>"8765" not in "9876543"
False
Page
4
Characters ASCII (Ordinal) Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD' True
>>> 'aBcD'<='abCd'
True
Example:
>>> ord('b') 98
>>> chr(65) 'A'
Page
5
6.5 Slice operator with Strings:
The slice operator slices a string using a range of indices.
Syntax:
string-name[start:end]
where start and end are integer indices. It returns a string from the index start to end-1.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
d a t a s t r u c t u r e
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example:
>>> str="data structure"
>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
' ' #returns empty string
>>> str[:14] # Missing index before colon is considered as
0. 'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of
string) 'data structure'
>>> str[7:] 'ructure'
>>> str[4:]+str[:4]
Page
6
' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original
string 'data structure'
>>> str[8:]+str[:8]
'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
Slice operator with step index:
Slice operator with strings may have third index. Which is known as step. It is optional.
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[2:9:2]
't tu'
>>> str[-11:-3:3]
'atc'
>>> str[: : -1] # reverses a
string 'erutcurts atad'
Interesting Fact: Index out of bounds causes error with strings but slicing a string outside the
index does not cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the
bounds ' ' # returns empty string
Page
7
Reason: When you use an index, you are accessing a particular character of a string, thus the
index must be valid and out of bounds index causes an error as there is no character to return
from the given index.
But slicing always returns a substring or empty string, which is valid sequence.
Page
9
Programs related to Strings:
1. Write a program that takes a string with multiple words and then capitalize the
first letter of each word and forms a new string out of it.
Solution:
s1=input("Enter a string : ")
length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!
=''): s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized wrds string: ", s2)
2. Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\
n")) str=input("Enter a string: ")
if choice==1:
s1=[Link]()
print(s1)
Page
10
elif choice==2:
s1=[Link]()
print(s1)
else:
print("Invalid choice entered")
Page
11
CHAPTER-9
LISTIN
PYTHON
7.1 Introduction:
List String
Mutable Immutable
Element can be assigned at specified Element/character cannot be
index assigned at specified index.
Example: Example:
To create a list enclose the elements of the list within square brackets and separate the
elements by commas.
Syntax:
Example:
>>> L
>>> List
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> L1
['6', '7', '8', '5', '4', '6'] # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> L1
Page
13
enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements without square bracket[ ], it will be
considered as a tuple.
>>> L1
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes.
List-name[start:end] will give you elements between indices start to end-1.
The first item in the list has the index zero (0).
Example:
>>> number=[12,56,87,45,23,97,56,27]
Forward Index
0 1 2 3 4 5 6
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2
Backward Index
>>> number[2]
87
>>> number[-1]
27
>>> number[-8]
12
>>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index
Page
14
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]
Method-1:
Output:
s
u
n
d
a
y
Method-2
>>> day=list(input("Enter elements :"))
Enter elements : wednesday
>>> for i in range(len(day)):
print(day[i])
Output:
w
e
d
n
e
s
d
a
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
Page
15
Joining Operator: It joins two or more
lists. Example:
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
times. Example:
>>> L1*3
>>> 3*L1
Slice Operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2]
>>> number[4:20]
>>> number[-1:-6] [ ]
>>> number[-6:-1]
Page
16
>>> number[0:len(number)]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> number[1:6:2]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
>>> number[2:4]=["computer"]
>>> number
Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27]
>>> number=[12,56,87,45,23,97,56,27]
Page
17
Comparison Operators:
Example:
Page
18
List Methods:
Consider a list:
company=["IBM","HCL","Wipro"]
S. Function
Description Example
No. Name
1 append( ) To add element to the list >>> [Link]("Google")
at the end. >>> company
Syntax: ['IBM', 'HCL', 'Wipro', 'Google']
[Link] (element)
Error:
>>>[Link]("infosys","microsoft") # takes exactly one
element TypeError: append() takes exactly one argument (2 given)
4 index( ) Returns the index of the >>> company = ["IBM", "HCL", "Wipro",
first element with the "HCL","Wipro"]
specified value. >>> [Link]("Wipro")
Syntax: 2
[Link](element)
Error:
>>> [Link]("WIPRO") # Python is case-sensitive
language ValueError: 'WIPRO' is not in list
Page
19
>>> [Link](2) # Write the element, not index
ValueError: 2 is not in list
5 insert( ) Adds an element at the >>>company=["IBM","HCL","Wipro"]
specified position. >>> [Link](2,"Apple")
>>> company
Syntax: ['IBM', 'HCL', 'Apple', 'Wipro']
[Link](index, element)
>>> [Link](16,"Microsoft")
>>> company
['IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
>>> [Link](-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
[]
Page
20
9 pop( ) Removes the element at >>>company=["IBM","HCL", "Wipro"]
the specified position and >>> [Link](1)
returns the deleted 'HCL'
element. >>> company
Syntax: ['IBM', 'Wipro']
[Link](index)
>>> [Link]( )
The index argument is
'Wipro'
optional. If no index is
specified, pop( ) removes and
returns the last item in the list.
Error:
>>>L=[ ]
>>>[Link]( )
IndexError: pop from empty list
10 copy( ) Returns a copy of the list. >>>company=["IBM","HCL", "Wipro"]
>>> L=[Link]( )
Syntax: >>> L
[Link]( ) ['IBM', 'HCL', 'Wipro']
11 reverse( ) Reverses the order of the >>>company=["IBM","HCL", "Wipro"]
list. >>> [Link]()
Syntax: >>> company
[Link]( ) ['Wipro', 'HCL', 'IBM']
Takes no argument,
returns no list.
Page
21
12. sort( ) Sorts the list. By default >>>company=["IBM","HCL", "Wipro"]
in ascending order. >>>[Link]( )
>>> company
Syntax: ['HCL', 'IBM', 'Wipro']
[Link]( )
To sort a list in descending order:
>>>company=["IBM","HCL", "Wipro"]
>>> [Link](reverse=True)
>>> company
['Wipro', 'IBM', 'HCL']
Page
22
Deleting the elements from the list using del statement:
Syntax:
list slice
Example:
>>> L=[10,20,30,40,50]
>>> L
>>> L= [10,20,30,40,50]
>>> L
>>> del L # deletes all elements and the list object too.
>>> L
Page
23
Difference between del, remove( ), pop( ), clear( ):
S.
del remove( ) pop( ) clear( )
No.
S.
append( ) extend( ) insert( )
No.
Adds an element at the
Adds single element in the end Add a list in the end of specified position.
1
of the list. the another list
(Anywhere in the list)
Takes one list Takes two arguments,
2 Takes one element as argument
as argument position and element.
The length of the list
The length of the list will The length of the list
3 will increase by the
increase by 1. will increase by 1.
length of inserted list.
Page
24
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
Page
26
CHAPTER-10
TUPLEIN
PYTHON
8.1 INTRODUCTION:
>>> T
>>> T=(3) #With a single element without comma, it is a value only, not a tuple
>>>
T3
>>> T= (3, ) # to construct a tuple, add a comma after the single element
>>>
T (3,)
Page
27
>>> T1=3, # It also creates a tuple with single element
>>>
T1 (3,)
>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
('h', 'e', 'l', 'l', 'o')
>>> T3=('hello','python')
>>> T3
('hello', 'python')
>>> T=(5,10,(4,8))
>>> T
>>> T
Page
28
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>> T1
('4', '5', '6', '7', '8') # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> T1
>>> type(T1)
<class 'int'>
>>> T2
(1, 2, 3, 4, 5)
>>> T3
Page
29
8.3 Accessing Tuples:
Tuples are very much similar to lists. Like lists, tuple elements are also indexed.
Forward indexing as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………
The values stored in a tuple can be accessed using the slice operator ([ ] and [:])
with indexes.
tuple-name[start:end] will give you elements between indices start to end-1.
The first item in the tuple has the index zero (0).
Example:
>>> alpha=('q','w','e','r','t','y')
Forward Index
0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1
Backward Index
>>> alpha[5]
'y'
>>> alpha[-4]
'e'
>>> alpha[46]
IndexError: tuple index out of range
>>> alpha[2]='b' #can’t change value in tuple, the value will remain
unchanged TypeError: 'tuple' object does not support item assignment
Page
30
8.4 Traversing a
Tuple: Syntax:
name: statement
Example:
Method-1
>>> alpha=('q','w','e','r','t','y')
>>> for i in alpha:
print(i)
Output:
q
w
e
r
t
y
Method-2
>>> for i in range(0, len(alpha)):
print(alpha[i])
Output:
q
w
e
r
t
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
Page
31
Joining Operator: It joins two or more
tuples. Example:
>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
(25, 50, 75, 5, 10, 15)
>>> T1 + (34)
TypeError: can only concatenate tuple (not "int") to tuple
>>> T1 + (34, )
times. Example:
>>> T1*2
>>> T2=(10,20,30,40)
>>> T2[2:4]*3
Slice Operator:
>>>alpha=('q','w','e','r','t','y')
'e')
't', 'y')
>>> alpha[-1:-5]
Page
32
()
>>> alpha[-5:-1]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> alpha[1:5:2]
('w', 'r')
Comparison Operators:
Example:
[Link] Page
33
False
>>> T1<=T2
True
Consider a tuple:
subject=("Hindi","English","Maths","Physics")
S. Function
Description Example
No. Name
1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths","Physics”)
Syntax: >>> len(subject)
len (tuple-name) 4
2 max( ) Returns the largest value >>> max(subject)
from a tuple. 'Physics'
Syntax:
max(tuple-name)
Error: If the tuple contains values of different data types, then it will give an error
because mixed data type comparison is not possible.
Page
34
tuple- >>> [Link]("Maths")
[Link](element)
2
5 count( ) Return the number of >>> [Link]("English")
times the value appears.
Syntax: 1
tuple-
[Link](element)
Example:
>> T=(2,4,6,8,10,12,14)
But you can delete a complete tuple with del statement as:
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T
Page
35
CHAPTER-9
DICTIONARYINPYTHON
9.1 INTRODUCTION:
Syntax:
Example:
>>> marks
>>> D
{ }
{'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78} # there is no guarantee
order.
Page
36
Note: Keys of a dictionary must be of immutable types, such as string, number, tuple.
Example:
>>> D1={[2,3]:"hello"}
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
In the above case the keys are not enclosed in quotes and equal sign is
used for assignment rather than colon.
>>> marks
>>> marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))
>>> marks
Page
37
In this case the keys and values are enclosed separately in parentheses and are given as
argument to the zip( ) function. zip( ) function clubs first key with first value and so on.
separately: Example-a
>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
# list as argument passed to dict( ) constructor contains list type elements.
>>> marks
Example-b
>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))
>>> marks
Example-c
>>> marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))
>>> marks
Page
38
9.3 ACCESSING ELEMENTS OF A DICTIONARY:
Syntax:
dictionary-name[key]
Example:
>>> marks["Maths"]
81
KeyError: 'English'
Lookup : A dictionary operation that takes a key and finds the corresponding value, is
called lookup.
Syntax:
statement
Page
39
Example:
OUTPUT:
physics : 75
Chemistry : 78
Maths : 81
CS : 78
Syntax:
dictionary-name[key]=value
Example:
>>> marks
>>> marks
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
Page
40
9.6 DELETE ELEMENTS FROM A DICTIONARY:
(iii)using popitem()
Syntax:
del dictionary-name[key]
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> marks
(ii) Using pop( ) method: It deletes the key-value pair and returns the value of deleted
element.
Syntax:
[Link]( )
Example:
>>> marks
>>> [Link]('Maths')
81
Page
41
(iii) Using popitem( ) method: It removes and returns the last added key- value pair in the
dictionary
Example:
Output:
(i) in : it returns True if the given key is present in the dictionary, otherwise False.
(ii) not in : it returns True if the given key is not present in the dictionary, otherwise
False.
Example:
>>> 'Chemistry' in
marks True
marks False
>>> 78 in marks # in and not in only checks the existence of keys not
values False
However, if you need to search for a value in dictionary, then you can use in operator
with the following syntax:
Syntax:
Page
42
value in dictionary-name. values( )
Example:
>>> 78 in [Link]( )
True
Page
43
9.8 DICTIONARY FUNCTIONS:
S. Function
Description Example
No. Name
1 len( ) Find the length of
a dictionary. >>> marks = { "physics" : 75,
Syntax: "Chemistry" : 78, "Maths" : 81, "CS":78
len (dictionary-name) }
>>> len(marks) 4
2 clear( ) removes all
elements >>> marks = { "physics" : 75,
from the dictionary "Chemistry" : 78, "Maths" : 81, "CS":78
}
Syntax:
[Link]( )
>>> [Link]( )
>>> marks
{}
>>> [Link]('Hindi')
>>>
4 items( ) returns all elements as a
sequence of (key,value) >>> marks = { "physics" : 75,
tuples in any order. "Chemistry" : 78, "Maths" : 81, "CS":78 }
Syntax: >>> [Link]()
[Link]( )
dict_items ([('physics', 75), ('Chemistry',
78), ('Maths', 81), ('CS', 78)])
Page
44
5 keys( ) Returns all keys in the
form of a list. >>> marks = { "physics" : 75, "Chemistry" :
Syntax: 78, "Maths" : 81, "CS":78 }
[Link]( )
>>> [Link]()
dict_keys(['physics','Chemistry', 'Maths',
'CS'])
6 values( ) Returns all values in the
form of a list. >>> marks = { "physics" : 75, "Chemistry" :
Syntax: 78, "Maths" : 81, "CS":78 }
[Link]( )
>>> [Link]()
>>> a
9 max() Returns the maximum key >>> num={'a':4,'b':2,'c':3}
print(max(num))
>>> c
Page
45
12 update( ) Merges two dictionaries. Example:
Already present elements >>> marks1 = { "physics" : 75, "Chemistry" :
are override. 78, "Maths" : 81 }
>>> marks2 = { "Hindi" : 80, "Chemistry" :
Syntax:
[Link](dictionary2)
88, "English" : 92 }
>>> [Link](marks2)
>>> marks1
{'physics': 75, 'Chemistry': 88, 'Maths': 81,
'Hindi': 80, 'English': 92}
Example:
>>> marks1 = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks2 = { "Hindi" : 80, "Chemistry" : 88, "English" : 92 }
>>> [Link](marks2)
>>> marks1
{'physics': 75, 'Chemistry': 88, 'Maths': 81, 'CS': 78, 'Hindi': 80, 'English': 92}
Page
46
Page
47