Strings: After Studying This Lesson, Students Will Be Able To
Strings: After Studying This Lesson, Students Will Be Able To
Strings
Introduction
In python, consecutive sequence of characters is known as a string. An individual
character in a string is accessed using a subscript (index). The subscript should always
be an integer (positive or negative). A subscript starts from 0.
Example
>>>myfirst=“Save Earth”
>>>print myfirst
Save Earth
>>>print myfirst[0]
168
To access the fourth character of the string
>>>print myfirst[3]
>>>print myfirst[-1]
>>h
>>>print myfirst[-3]
String A H E L L O
Positive Index 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1
Subscript 0 or –ve n(where n is length of the string) displays the first element.
Note: Python does not support character data type. A string of size 1 can be treated as
characters.
169
Creating and initializing strings
A literal/constant value to a string can be assigned using a single quotes, double quotes
or triple quotes.
Example
As shown in example 2, to include the single quote within the string it should be
preceded by a backslash.
170
In the above example, backslash (\) is used as an escape sequence. An escape
sequences is nothing but a special character that has a specific function. As shown
above, backslash (\) is used to escape the double quote.
Example
>>>raw_input()
Right to education
„Right to education‟
As soon as the interpreter encounters raw_input method, it waits for the user to
key in the input from a standard input device (keyboard) and press Enter key. The
input is converted to a string and displayed on the screen.
Note: raw_input( ) method has been already discussed in previous chapter in detail.
Example
171
Python interpreter was not able associate appropriate data type with the entered
data. So a NameError is shown. The error can be rectified by enclosing the given
input i.e. hello in quotes as shown below
Example
>>>str='honesty'
>>>str[2]='p'
Traversing a string
Traversing a string means accessing all the elements of the string one after the other by
using the subscript. A string can be traversed using: for loop or while loop.
String traversal using for loop String traversal using while loop
A=‟Welcome‟ A=‟Welcome‟
>>>for i in A: >>>i=0
print i >>>while i<len(A)
W print A[i]
172
e i=i+1
l W
c e
o l
m c
e o
m
e
Strings Operations
173
string on the left hand side „Save Earth Save Earth Save Earth
times the value on right ‟
hand side.
174
More on string Slicing
Consider the given figure
String A S A V E E A R T H
Positive Index 0 1 2 3 4 5 6 7 8 9
Example
>>>A=‟Save Earth‟
av
The print statement prints the substring starting from subscript 1 and ending at
subscript 3 .
Example
>>>print A[3:]
„e Earth‟
Omitting the second index, directs the python interpreter to extract the substring till the
end of the string
Example
>>>print A[:3]
Sav
Omitting the first index, directs the python interpreter to extract the substring before
the second index starting from the beginning.
175
Example
>>>print A[:]
„Save Earth‟
Omitting both the indices, directs the python interpreter to extract the entire string
starting from 0 till the last index
Example
>>>print A[-2:]
„th‟
For negative indices the python interpreter counts from the right side (also shown
above). So the last two letters are printed.
Example
>>>Print A[:-2]
„Save Ear‟
Omitting the first index, directs the python interpreter to start extracting the substring
form the beginning. Since the negative index indicates slicing from the end of the string.
So the entire string except the last two letters is printed.
Note: Comparing strings using relational operators has already been discussed in the
previous chapter
176
upper case >>>print str.capitalize()
Welcome
177
contains only numbers. false
Otherwise it returns False.
178
right of the string. Teach India Movement
179
LOWER
Note: In the table given above, len( ) is a built in function and so we don‟t need
import the string module. For all other functions import string statement is required
for their successful execution.
180
Let‟s discuss some interesting strings constants defined in string module:
string.ascii_uppercase
Example
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase
Example
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
string.ascii_letters
The command displays a string containing both uppercase and lowercase characters.
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits
>>> string.digits
'0123456789'
string.hexdigits
>>> string.hexdigits
'0123456789abcdefABCDEF'
181
string.octdigits
>>> string.octdigits
'01234567'
string.punctuations
>>> string.punctuations
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}-'
string.whitespace
The command displays a string containing all ASCII characters that are considered
whitespace. This includes the characters space, tab, linefeed, return, formfeed, and
vertical tab.
>>> string.whitespace
'\t\n\x0b\x0c\r '
string.printable
The command displays a string containing all characters which are considered printable
like letters, digits, punctuations and whitespaces.
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!
"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}- \t\n\r\x0b\x0c'
Note: Import string module to get the desired results with the commands mentioned
above.
182
Programs using string functions and operators
defpalin():
l=len(str)
p=l-1
index=0
while (index<p):
if(str[index]==str[p]):
index=index+1
p=p-1
else:
break
else:
def lettercount():
word = 'pineapple'
count = 0
if letter == 'p':
count = count + 1
print(count)
183
Regular expressions and Pattern matching
A regular expression is a sequence of letters and some special characters (also called
meta characters). These special characters have symbolic meaning. The sequence
formed by using meta characters and letters can be used to represent a group of
patterns.
For example
str= “Ram$”
The pattern “Ram$” is known as a regular expression. The expression has the meta
character „$‟. Meta character „$‟ is used to match the given regular expression at the end
of the string. So the regular expression would match the string „SitaRam‟ or „HeyRam‟
but will not match the string „Raman‟.
string1='SitaRam' string1='SitaRam'
if if re.search('Sita$',string1):
re.search('Ram$',string1): print "String Found"
print "String Found" else :
else : print" No Match"
print" No Match" Output
Output: No Match
String Found
As shown in the above examples, Regular expressions can be used in python for
matching a particular pattern by importing the re module.
184
Now let‟s learn how the meta characters are used to form regular expressions.
185
6 ? Used to specify that the previous wate?r
character can be matched either The regular expression
once or zero times would only match strings
like watr or water
re.compile()
The re.compile( ) function will compile the pattern into pattern objects. After the
compilation the pattern objects will be able to access methods for various operations
like searching and subsitutions
Example
import re
p=re.compile(„hell*o‟)
re.match()
The match function is used to determine if the regular expression (RE) matches at the
beginning of the string.
re.group()
Example
>>>P=re.compile(„hell*o‟)
>>>m.group()
„hello‟
186
re.start()
re.end()
re.span()
The span function returns the tuple containing the (start, end) positions of the match
Example
>>> import re
>>> P=re.compile('hell*o')
>>> m.start()
>>> m.end()
>>> m.span()
(0, 5)
re.search()
The search function traverses through the string and determines the position where the
RE matches the string
Example
>>> m.start()
15
>>> m.end()
187
20
>>> m.group()
'hello'
>>> m.span()
(15, 20)
Re.findall()
The function determines all substrings where the RE matches, and returns them as a list.
Example
>>> m
['hello', 'hello']
re.finditer()
The function determines all substrings where the RE matches, and returns them as an
iterator.
Example
>>> m
print match.span()
(0, 5)
(24, 29)
188
Script 1: Write a script to determine if the given substring is present in the string.
def search_string():
import re
substring='water'
search1=re.search(substring,'Water water everywhere but not a drop to drink')
if search1:
position=search1.start()
print "matched", substring, "at position", position
else:
print "No match found"
Script 2: Write a script to determine if the given substring (defined using meta
characters) is present in the given string
def metasearch():
import re
p=re.compile('sing+')
search1=re.search(p,'Some singers sing well')
if search1:
match=search1.group()
index=search1.start()
lindex=search1.end()
print "matched", match, "at index", index ,"ending at" ,lindex
else:
print "No match found"
189
EXERCISE
1. Input a string “Green Revolution”. Write a script to print the string in reverse.
2. Input the string “Success”. Write a script of check if the string is a palindrome or
not
3. Input the string “Successor”. Write a script to split the string at every occurrence of
the letter s.
4. Input the string “Successor”. Write a script to partition the string at the occurrence
of the letter s. Also Explain the difference between the function split( ) and
partition().
22
333
4444
55555
6. What will be the output of the following statement? Also justify for answer.
>>> str.replace('o','*')
>>>str.istiltle()
190
10. Write a program to print alternate characters in a string. Input a string of your own
choice.
11. Input a string „Python‟. Write a program to print all the letters except the letter‟y‟.
i) To replace all the occurrences of letter „a‟ in the string with „*‟
def metasearch():
import re
p=re.compile('sing+')
if search1:
match=search1.group()
index=search1.start()
lindex=search1.end()
else:
191
print "No match found"
What will be the output of the above script if search() from the re module is
replaced by match () of the re module. Justify your answer
14. What will be the output of the script mentioned below? Justify your answer.
def find():
import re
p=re.compile('sing+')
print search1
>>> str[5]='p'
192
Chapter 2
Lists
Introduction
Like a String, list also is sequence data type. It is an ordered set of values enclosed in
square brackets []. Values in the list can be modified, i.e. it is mutable. As it is set of
values, we can use index in square brackets [] to identify a value belonging to it. The
values that make up a list are called its elements, and they can be of any type.
We can also say that list data type is a container that holds a number of elements in a
given order. For accessing an element of the list, indexing is used.
It will provide the value at „index+1‟ in the list. Index here, has to be an integer value-
which can be positive or negative. Positive value of index means counting forward from
beginning of the list and negative value means counting backward from end of the list.
Remember the result of indexing a list is the value of type accessed from the list.
0, -size 1st
1, -size +1 2nd
193
2, -size +2 3rd
.
.
.
Please note that in the above example size is the total number of elements in the list.
iv) >>>L4 = [“abc”, 10, 20] # list with different types of elements
You will study about Nested lists in later parts of the chapter.
To change the value of element of list, we access the element & assign the new value.
Example
>>> L1 [2] = 5
[1, 2, 5, 4]
Here, 3rd element of the list (accessed using index value 2) is given a new value, so
instead of 3 it will be 5.
194
L1 0 1 L2 0 Delhi L3
1 2 1 Chennai
2 3 2 Mumbai
3 4
Note: List index works the same way as String index, which is:
An integer value/expression can be used as index.
An Index Error appears, if you try and access element that does not exist in the
list.
An index can have a negative value, in that case counting happens from the end
of the list.
Creating a list
List can be created in many ways:
Example
L5=L1 [:]
>>>print L5
L6 = L1 [0:2]
>>>print L6
Example
>>>n = 5
195
>>>l = range(n)
>>>print l
[0, 1, 2, 3, 4]
Example
>>> print S
In mathematical terms, S can be defined as S = {x2 for: x in (0.....9)}. So, we can say
that list comprehension is short-hand for creating list.
Example
>>> A = [3, 4, 5]
Here B will be created with the help of A and its each element will be thrice of
element of A.
>>> print B
>>>B = [ ]
>>>for i in A
B. append (i*3)
Example
>>> print B
>>>C = [i for i in S if i % 2 = = 0]
196
>>>print C
Example
>>>l = list ( )
>>>print l
[ ] # empty list
Or
L = list (sequence)
Example
>>>print L
[1, 2, 3, 4]
A single new list is created every time, you execute [ ]. We have created many
different lists each using [ ]. But if a list is assigned to another variable, a new list
is not created.
i) A=B=[ ]
Example
>>> print A, B
ii) A=[]
B=A
197
Example
>>> A = [1, 2, 3]
>>> B = A
>>> print A, B
[1, 2, 3] [1, 2, 3]
List Slices
Slice operator works on list also. We know that a slice of a list is its sub-list. For creating
a list slice, we use
[n:m] operator.
>>>print L5 [0]
>>>print L5 [2]
[6, 7, 8]
as the 3rd element of this list is a list. To access a value from this sub-list, we will use
This will return the part of the list from nth element to mth element, including the first
element but excluding the last element. So the resultant list will have m-n elements in it.
>>> L1 [1:2]
will give
[2]
198
Slices are treated as boundaries, and the result will contain all the elements between
boundaries.
Where start, stop & step- all three are optional. If you omit first index, slice starts from
„0‟ and omitting of stop will take it to end. Default value of step is 1.
Example
>>>L2 [0:2]
[“Delhi”, “Chennai”]
Example
>>>list [4:] # will produce a list containing all the elements from 5th position
till end
[50, 60]
Example
>>>list [:3]
>>>list [:]
Example
60
199
Note: Since lists are mutable, it is often recommended to make a copy of it before
performing operation that change a list.
Traversing a List
Let us visit each element (traverse the list) of the list to display them on screen. This can
be done in many ways:
(i) i=0
while i < 4:
print L1 [i],
i+=1
1254
print i,
(iii) i=0
print L1 [i],
i+=1
OR
i= 0
L = len (L1)
while i < L :
print L1 [i],
i+=1
200
Here len( ) function is used to get the length of list L1. As length of L1 is 4, i will take
value from 0 to 3.
print L1 [i],
Using 2nd way for transversal will only allow us to print the list, but other ways can also
be used to write or update the element of the list.
In 4th way, range ( ) function is used to generate, indices from 0 to len -1; with each
iteration i gets the index of next element and values of list are printed.
Example
for i in [ ]:
print i
i=1
print L1 [-i],
i += 1
In this case, Python will add the length of the list to index and then return the
index value and accesses the desired element. In this loop execution for a positive
value of „i‟ L1 [-i] will result into L1 [len (L1)-i] for i=1, L1 [4-1] will be printed. So
resultant of the loop will be 4 5 2.
201
L1. append (70)
This will add 70 to the list at the end, so now 70 will be the 5th element of the list, as it
already have 4 elements.
>>> print L1
[1, 2, 5, 4, 70]
Example
>>>print L4
Using append ( ), only one element at a time can be added. For adding more than one
element, extend ( ) method can be used, this can also be used to add elements of another
list to the existing one.
Example
>>> print L1
will add all the elements of list „A‟ at the end of the list „L1‟.
>>>print A
Example
>>>B.extend (c)
>>>print B
202
[2009, 2011, „abc‟, „xyz‟, „pqr‟, „mn‟]
Example
>>> print L1
will produce
Example
>>>print A
will produce
[10, 100]
As lists are sequences, they support many operations of strings. For example, operator +
& * results in concatenation & repetition of lists. Use of these operators generate a new
list.
Example
>>> a= L1+L2
will produce a 3rd list a containing elements from L1 & then L2. a will contain
[1, 10, 20, 4, 70, 100, 90, 80, 50, “Delhi”, “Chennai”, “Mumbai”]
203
Example
[1, 2, 3, 4, 5, 6]
Example
>>> b = L1*2
>>> print b
[[1, 10, 20, 4, 70, 100, 90, 80, 50, 1, 10, 20, 4, 70, 100, 90, 80, 50]
Example
>>> [„Hi!‟]* 3
It is important to know that ‘+’ operator in lists expects the same type of sequence on
both the sides otherwise you get a type error.
If you want to concatenate a list and string, either you have to convert the list to string
or string to list.
Example
Deleting Elements
It is possible to delete/remove element(s) from the list. There are many ways of doing
so:
(ii) If the element is known, not the index, remove ( ) can be used.
(iii) To remove more than one element, del ( ) with list slice can be used.
204
Let us study all the above methods in details:
Pop ( )
It removes the element from the specified index, and also return the element which was
removed.
List.pop ([index])
Example
>>> a= L1.pop (1) # here the element deleted will be returned to ‘a’
>>> print L1
>>> print a
>>>L1.pop ( )
50
del removes the specified element from the list, but does not return the deleted
value.
>>> print L1
remove ( )
In case, we know the element to be deleted not the index, of the element, then remove (
) can be used.
205
>>> print L1
Examples
>>>print L1
[1, 5, 80]
will remove 2nd and 3rd element from the list. As we know that slice selects all the
elements up to 2nd index but not the 2nd index element. So 4th element will remain in the
list.
>>> L5 [1:2] = [ ]
>>>print L5
Note:
(i) All the methods, modify the list, after deletions.
(ii) If an out of range index is provided with del ( ) and pop ( ), the code will result
in to run-time error.
(iii) del can be used with negative index value also.
206
Its syntax is
Index specifies the position (starting from 0) where the element is to be inserted. Item is
the element to be inserted in the list. Length of list changes after insert operation.
Example
>>>print L1
will produce
Note: If the index specified is greater then len (list) the object is inserted in the last
and if index is less than zero, the object is inserted at the beginning.
>>>print L1
will produce
reverse ( )
This method can be used to reverse the elements of the list in place
list.reverse ( )
Method does not return anything as the reversed list is stored in the same variable.
Example
>>> L1.reverse ( )
207
>>> print L1
will produce
>>>L1 [: : -1]
As this slices the whole sequence with the step of -1 i.e. in reverse order.
sort ( )
For arranging elements in an order Python provides a method sort ( ) and a function
sorted ( ). sort ( ) modifies the list in place and sorted ( ) returns a new sorted list.
Parameters mentioned in [ ] are optional in both the cases. These parameters allow us to
customize the function/method.
cmp, argument allow us to override the default way of comparing elements of list. By
default, sort determines the order of elements by comparing the elements in the list
against each other. To overside this, we can use a user defined function which should
take two values and return -1 for ‘less than’, 0 for ‘equal to’ and 1 for „greater than‟.
Example
The parameter ‘key’ is for specifying a function that transforms each element of list
before comparison. We can use predefined functions or a user defined function here. If
its user defined then, the function should take a single argument and return a key
which can be used for sorting purpose.
Reverse parameter can have a boolean value which is used to specify the order of
arranging the elements of list. Value ‘True’ for reverse will arrange the elements of list
in descending order and value ‘False’ for reverse will arrange the elements in ascending
order. Default value of this parameter is False.
208
sorted ( ) function also behaves in similar manner except for it produce a new sorted
list, so original is not changed. This function can also be used to sort any iterable
collection. As sort ( ) method does not create a new list so it can be little faster.
Example
>>> L1.sort ( )
>>> print L1
will produce
>>> L2.sort ( )
>>> print L2
will produce
will produce
Here we have specified len ( ) built in function, as key for sorting. So the list will get
sorted by the length of the strings, i.e., from shorted to longest.
sort will call len ( ) function for each element of list and then these lengths will be used
for arranging elements.
>>> L4.sort ( )
>>> print L4
will produce
209
[10, 20, 30, „abc‟]
>>>L4.sort (reverse = True)
[„abc‟, 30, 20, 10]
>>> def compare (str):
... return len (str)
>>> L2.sort (key=compare)
>>> L2
[„Delhi‟, „Mumbai‟, „Chennai‟]
List as arguments
When a list is passed to the function, the function gets a reference to the list. So if the
function makes any changes in the list, they will be reflected back in the list.
Example
L [i] += 10
>>> X = [1, 2, 3, 4, 5]
>>> print X
Here parameter „L‟ and argument „X‟ are alias for same object. Its state diagram will
look like
210
Note: Here, it becomes important to distinguish between the operations which
modifies a list and operation which creates a new list. Operations which create a new
list will not affect the original (argument) list.
Let‟s look at some examples to see when we have different lists and when an alias is
created.
>>> a = [2, 4, 6]
>>> b = a
will map b to a. To check whether two variables refer to same object (i.e. having same
value), we can use „is‟ operator. So in our example:
>>> a is b
>>> a = [2, 4, 6]
>>> b = [2, 4, 6]
>>> a is b
False
In first example, Python created one list, reference by a & b. So there are two references
to the same object b. We can say that object [2, 4, 6] is aliased as it has more than one
name, and since lists are mutable. So changes made using „a‟ will affect „b‟.
>>> a [1] = 10
>>> print b
will print
[2, 10, 6]
211
Matrix implementation using list
We can implement matrix operation using list. Matrix operation can be implemented
using nested list. List inside another list is called nested list.
Example
Write a program to input any matrix with mXn, and print the number on the output
screen in matrix format.
Matrix creation
Program 1
212
Output
>>>
output is
10 20 30
40 50 60
70 80 90
>>>
Program 2
import random
for i in range(m):
213
for j in range(n):
a[i][j]=input()
for i in range(m):
for j in range(n):
print a[i][j],'\t',
Output
>>>
output is
1 2 3
4 5 6
7 8 9
>>>
214
Matrix Addition
Write a program to input any two matrices and print sum of matrices.
import random
for i in range(m1):
for j in range(n1):
a[i][j]=input()
for i in range(2):
for j in range(2):
b[i][j]=input()
for i in range(m1):
for j in range(n1):
c[i][j]=a[i][j]+b[i][j]
print c[i][j],'\t',
else
215
Output
>>>
output is
3 3
3 3
Example
Write a program to input any two matrices and print product of matrices.
import random
for i in range(m1):
for j in range(n1):
a[i][j]=input()
216
m2=input ("Enter total number of rows in the second matrix")
for i in range(m2):
for j in range(n2):
b[i][j]=input()
if (n1==m2):
for i in range(m1):
for j in range(n2):
c[i][j]=0
for k in range(n1):
c[i][j]+=a[i][k]*b[k][j]
print c[i][j],'\t',
else:
Output
>>>
217
Enter total number of columns in the second matrix2
4 4
4 4
>>>
Example
Write a program to input any matrix and print both diagonal values of the matrix.
import random
if (m==n):
for i in range(m):
for j in range(n):
a[i][j]=input()
for i in range(m):
print a[i][i],'\t',
k=m-1
for j in range(m):
print a[j][k],'\t',
218
k-=1
else:
Output
>>>
First diagonal
1 5 9
Second diagonal
3 5 7
>>>
Example
Write a program to pass any list and to arrange all numbers in descending order.
219
def arrange (l,n):
for i in range(n-1):
for j in range(n-i-1):
if l[j]>l[j+1]:
temp=l[j]
l[j]=l[j+1]
l[j+1]=temp
Output
>>>
>>> l=[7,5,8,2,9,10,3]
>>> print l
[10, 9, 8, 7, 5, 3, 2]
>>>
Example
Write a program to input nXm matrix and find sum of all numbers using function.
Function:
def summat(a,m,n):
s=0
for i in range(m):
for j in range(n):
s+=a[i][j]
return s
220
Function call
import random
import mataddition
for i in range(m):
for j in range(n):
a[i][j]=input()
s=mataddition.summat(a,m,n)
print s
Output
>>>
10
>>>
Example
count = -1
for list in a:
221
count + = 1
print item,
123
45
678
222
EXERCISE
1. Define list
b) a= [1, 2, 3, None, ( ), [ ]}
print len(a)
(iii) 5 (iv) 6
(v) 7
A=[2,4,6,8,10]
L=len(L)
S=0
for I in range(1,L,2):
S+=A[I]
print “Sum=”,S
l=range(n)
print l
for i in (n);
l[i]=input("enter element")
223
print "All elements in the list on the output screen"
for i on range(n):
print l[i]
5. Write a function group of list (list, size) that takes a list and splits into smaller list
of given size.
7. For each of the expression below, specify its type and value. If it generates error,
write error.
(i) x[0]
(ii) x[2]
(iii) x[-1]
(iv) x[0:1]
(v) 2 in x
(vi) x[0]=8
8. For each of the expression below, specify its type and value. If it generates error,
write error:
List A= [1, 4, 3, 0]
(ii) List A
224
(vii) List B.pop ( )
LAB EXERCISE
2. Write a function that takes a list of numbers and returns the cumulative sum; that
is, a new list where the its element is the sum of the first i+1 elements from the
original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].
3. Write a function called chop that takes a list and modifies it, removing the first and
last elements, and returns None. Then write a function called middle that takes a list
and returns a new list that contains all but the first and last elements.
4. Write a function called is_sorted that takes a list as a parameter and returns True if
the list is sorted in ascending order and False otherwise. You can assume (as a
precondition) that the elements of the list can be compared with the relational
operators <, >, etc.
For example, is_sorted ([1, 2, 2]) should return True and is_sorted ([‘b’, ‘a’]) should
return False.
5. Write a function called remove_duplicates that takes a list and returns a new list
with only the unique elements from the original. Hint: they don‟t have to be in the
same order.
6. Write a function that takes in two sorted lists and merges them. The lists may not
be of same length and one or both may be empty. Don‟t use any Python built-in
methods or functions.
225
7. Create a list that contains the names of 5 students of your class. (Do not ask for
input to do so)
(ii) Ask the user to input one name and append it to the list
(iv) Ask user to input a number. Print the name that has the number as index
(Generate error message if the number provided is more than last index
value).
(v) Add “Kamal” and “Sanjana” at the beginning of the list by using „+‟.
(vii) Ask the user to type a name. Check whether that name is in the list. If exist,
delete the name, otherwise append it at the end of the list.
8. Use the list of student names from the previous exercise. Create a for loop that asks
the user for every name whether they would like to keep the name or delete it.
Delete the names which the user no longer wants. Hint: you cannot go through a
list using a for loop and delete elements from the same list simultaneously because
in that way the for loop will not reach all elements. You can either use a second
copy of the list for the loop condition or you can use a second empty list to which
you append the elements that the user does not want to delete.
9. Write a function to find product of the element of a list. What happens when the
function is called with list of strings?
10. Write a program to input NXM matrix and find sum of all even numbers in the
matrix.
13. Write a program to find sum of rows and columns of the matrix.
226
Chapter 3
Dictionaries
What is dictionary?
A dictionary is like a list, but more in general. In a list, index value is an integer, while
in a dictionary index value can be any other data type and are called keys. The key will
be used as a string as it is easy to recall. A dictionary is an extremely useful data storage
construct for storing and retrieving all key value pairs, where each element is accessed
(or indexed) by a unique key. However, dictionary keys are not in sequences and hence
maintain no left-to right order.
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called
keys) and a set of values. Each key maps a value. The association of a key and a value is
called a key-value pair.
Syntax:
Example
>>> A={1:"one",2:"two",3:"three"}
>>> print A
227
In the above example, we have created a list that maps from numbers to English words,
so the keys values are in numbers and values are in strings.
1 one
A =
2 two
3 three
>>>computer={'input':'keybord','output':'mouse','language':'python','os':'windows-
8',}
>>>
In the above example, we have created a list that maps from computer related things
with example, so here the keys and values are in strings. The order of the key-value
pairs is not in same order (ie. input and output orders are not same). We can get
different order of items in different computers. Thus, the order of items in a dictionary
is unpredictable.
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> print D
228
>>> D=dict()
>>> print D
{}
{} represents empty string. To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary values.
Example
>>> H=dict()
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
>>>
Traversing a dictionary
Let us visit each element of the dictionary to display its values on screen. This can be
done by using ‘for-loop’.
Example
Code
for i in H:
Output
>>>
>>>
229
OR
Code
for i in H:
Output
Four scanner
one keyboard
three printer
two Mouse
Example
Write a program to input total number of sections and class teachers’ name in 11 th class
and display all information on the output screen.
Code
classxi=dict()
i=1
while i<=n:
a=raw_input("enter section")
230
b=raw_input ("enter class teacher name")
classxi[a]=b
i=i+1
for i in classxi:
print "XI","\t",i,"\t",classxi[i]
Output
>>>
enter sectionA
enter sectionB
enter sectionC
XI A Leena
XI C Surpreeth
XI B Madhu
>>>
Syntax:
231
Example
>>> a={"mon":"monday","tue":"tuesday","wed":"wednesday"}
>>> a["thu"]="thursday"
>>> print a
>>>
Syntax:
Dic_name1.update (dic_name2)
Example
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
Example
{1: 10, 2: 30, 3: 30, 5: 40, 6: 60} # k>>> d1={1:10,2:20,3:30} # key 2 value is 20
>>> d1.update(d2)
>>> print d1
232
Removing an item from dictionary
We can remove item from the existing dictionary by using del key word.
Syntax:
del dicname[key]
Example
>>> A={"mon":"monday","tue":"tuesday","wed":"wednesday","thu":"thursday"}
>>> print A
>>>
Syntax:
returns 0 or 1 or -1
Example
>>>
D1={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursd
ay','fri':'Friday','sat':'Saturday'}
>>>
D2={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursd
ay','fri':'Friday','sat':'Saturday'}
>>> D3={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
233
1
>>> cmp(D3,D1)
-1
len( )
This method returns number of key-value pairs in the given dictionary.
Syntax:
len(d) #d dictionary
Example
>>> len(H)
clear ( )
It removes all items from the particular dictionary.
Syntax:
d.clear( ) #d dictionary
Example
>>> D={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
>>> print D
>>> D.clear( )
>>> print D
{}
234
get(k, x )
There are two arguments (k, x) passed in ‘get( )’ method. The first argument is key
value, while the second argument is corresponding value. If a dictionary has a given
key (k), which is equal to given value (x), it returns the corresponding value (x) of given
key (k). However, if the dictionary has no key-value pair for given key (k), this method
returns the default values same as given key value. The second argument is optional. If
omitted and the dictionary has no key equal to the given key value, then it returns
None.
Syntax:
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.get('wed',"wednesday") # corresponding value wed
'Wednesday'
>>> D.get("fri","monday") # default value of fri
'Friday'
>>> D.get("mon") # default value of mon
'Monday'
>>> D.get("ttu") # None
>>>
has_key( )
This function returns ‘True’, if dictionary has a key, otherwise it returns ‘False’.
Syntax:
Example
>>>
235
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.has_key("fri")
True
>>> D.has_key("aaa")
False
>>>
items( )
It returns the content of dictionary as a list of key and value. The key and value pair
will be in the form of a tuple, which is not in any particular order.
Syntax:
D.items() # D dictionary
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.items()
Note: items () is different from print command because, in print command dictionary
values are written in {}
keys()
It returns a list of the key values in a dictionary, , which is not in any particular order.
Syntax:
D.keys( ) #D dictionary
Example
>>>
236
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.keys()
>>>
values()
It returns a list of values from key-value pairs in a dictionary, which is not in any
particular order. However, if we call both the items () and values() method without
changing the dictionary's contents between these two (items() and values()), Python
guarantees that the order of the two results will be the same.
Syntax:
D.values() #D values
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.values()
>>> D.items()
Solved Examples
1. Write a python program to input ‘n’ names and phone numbers to store it in a
dictionary and to input any name and to print the phone number of that particular
name.
Code
phonebook=dict()
237
n=input("Enter total number of friends")
i=1
while i<=n:
a=raw_input("enter name")
phonebook[a]=b
i=i+1
name=raw_input("enter name")
f=0
l=phonebook.keys()
for i in l:
if (cmp(i,name)==0):
f=1
if (f==0):
Output
>>>
enter nameMona
enter nameSonu
enter nameRohan
enter nameSonu
238
Phone number= 45678956
>>>
2. Write a program to input ‘n’ employee number and name and to display all
employee’s information in ascending order based upon their number.
Code
empinfo=dict()
i=1
while i<=n:
a=raw_input("enter number")
b=raw_input("enter name")
empinfo[a]=b
i=i+1
l=empinfo.keys()
l.sort()
for i in l:
print i,'\t',empinfo[i]
Output
>>>
enter number555
enter nameArpit
enter number333
239
enter nameShilpa
enter number777
enter nameKush
enter number222
enter nameAnkita
enter number666
enter nameArun
Employee Information
222 Ankita
333 Shilpa
555 Arpit
666 Arun
777 Kush
>>>
A={1:100,2:200,3:300,4:400,5:500}
print A.items()
print A.keys()
print A.values()
Output
[(1, 100), (2, 200), (3, 300), (4, 400), (5, 500)]
[1, 2, 3, 4, 5]
240
4. Write a program to create a phone book and delete particular phone number using
name.
Code
phonebook=dict()
i=1
while i<=n:
a=raw_input("enter name")
phonebook[a]=b
i=i+1
name=raw_input("enter name")
del phonebook[name]
l=phonebook.keys()
for i in l:
print i,'\t',phonebook[i]
Output
>>>
enter nameLeena
enter nameMadhu
enter nameSurpreeth
241
enter phone number 9678543245
enter nameDeepak
enter nameAnuj
enter nameDeepak
Phonebook Information
Leena 9868734523
Surpreeth 9678543245
Madhu 9934567890
Anuj 9655442345
>>>
242
EXERCISE
1. Write the code to input any 5 years and the population of any city and print it on
the screen.
2. Write a code to input ‘n’ number of subject and head of the department and also
display all information on the output screen.
A={10:1000,20:2000,30:3000,40:4000,50:5000}
print A.items()
print A.keys()
print A.values()
4. Write a code to create customer’s list with their number & name and delete any
particular customer using his /her number.
5. Write a Python program to input ‘n’ names and phone numbers to store it in a
dictionary and print the phone number of a particular name.
c=dict()
n=input(Enter total number )
i=1
while i<=n
a=raw_input("enter place")
b=raw_input("enter number")
c(a)=b
i=i+1
print "place","\t","number"
for i in c:
print i,"\t",cla[i]
243
Chapter 4
Tuples
What is a Tuple?
A tuple is a sequence of values, which can be of any type and they are indexed by
integer. Tuples are just like list, but we can’t change values of tuples in place. Thus
tuples are immutable. The index value of tuple starts from 0.
>>> print T
But in the result, same tuple is printed using parentheses. To create a tuple with single
element, we have to use final comma. A value with in the parenthesis is not tuple.
Example
>>> T=(10)
>>> type(T)
<type 'int'>
Example
>>> t=10,
>>> print t
(10,)
244
Example
>>> T=(10,20)
>>> type(T)
<type 'tuple'>
Example
>>> T=('sun','mon','tue')
>>> print T
Example
>>> T=('P','Y','T','H','O','N')
>>> print T
Tuple Creation
If we need to create a tuple with a single element, we need to include a final comma.
Example
>>> t=10,
>>> print t
(10,)
Syntax:
T = tuple()
Example
>>> T=tuple()
245
>>> print T
()
Example
>>> t=(10,20,30,40)
>>> print t
>>> print t
Example
Code
t=tuple()
for i in range(n):
a=input("enter number")
t=t+(a,)
print t
246
Output
>>>
enter number10
enter number20
enter number30
output is
>>>
Code
t=tuple()
for i in range(n):
a=input("enter number")
t=t+(a,)
for i in range(n):
print t[i]
Output
>>>
enter number10
247
enter number20
enter number30
output is
10
20
30
>>>
We can also add new element to tuple by using list. For that we have to convert the
tuple into a list first and then use append() function to add new elements to the list.
After completing the addition, convert the list into tuple. Following example illustrates
how to add new elements to tuple using a list.
>>> print T
()
>>> l.append(20)
>>> print T
(10, 20)
>>> T=(0,)*10
>>> print T
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
Tuple Assignment
If we want to interchange (swap) any two variable values, we have to use temporary
variable. For example;
248
>>> A=10
>>> B=20
10 20
>>> T=A
>>> A=B
>>> B=T
20 10
Example
>>> T1=(10,20,30)
>>> T2=(100,200,300,400)
>>> print T1
>>> print T2
>>> print T1
>>> print T2
The left side is a tuple of variables, while the right side is a tuple of expressions. Each
value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.
249
The number of variables on the left and the number of values on the right have to be the
same:
Example
>>> T1=(10,20,30)
>>> T2=(100,200,300)
>>> t3=(1000,2000,3000)
>>> T1,T2=T2,T1,t3
T1,T2=T2,T1,t3
Here, two tuples are in the left side and three tuples are in right side. That is why, we
get errors. Thus, it is required to have same number of tuples in both sides to get the
correct result.
Example
>>> T1,T2,t3=t3,T1,T2
>>> print T1
>>> print T2
>>> print t3
Tuple Slices
Slice operator works on Tuple also. This is used to display more than one selected value
on the output screen. Slices are treated as boundaries and the result will contain all the
elements between boundaries.
250
Syntax is:
Where start, stop & step all three are optional. If we omit first index, slice starts from ‘0’.
On omitting stop, slice will take it to end. Default value of step is 1.
Example
>>> T=(10,20,30,40,50)
>>> T1=T[2:4]
>>> print T1
(30, 40)
In the above example, starting position is 2 and ending position is 3(4-1), so the selected
elements are 30 & 40.
>>> T[:]
>>> T[::2]
>>> T[:3]
>>> T[2:]
251
Tuple Functions
cmp( )
This is used to check whether the given tuples are same or not. If both are same, it will
return ‘zero’, otherwise return 1 or -1. If the first tuple is big, then it will return 1,
otherwise return -1.
Syntax:
cmp(t1,t2) #t1and t2 are tuples.
returns 0 or 1 or -1
Example
>>> T1=(10,20,30)
>>> T2=(100,200,300)
>>> T3=(10,20,30)
>>> cmp(T1,T2)
-1
>>> cmp(T1,T3)
0
>>> cmp(T2,T1)
1
len( )
It returns the number of items in a tuple.
Syntax:
len(t) #t tuples
Example
>>> T2=(100,200,300,400,500)
>>> len(T2)
5
252
max( )
It returns its largest item in the tuple.
Syntax:
max(t) #t tuples
returns maximum value among the given tuple.
Example
>>> T=(100,200,300,400,500)
>>> max(T)
500
min( )
It returns its smallest item in the tuple.
Syntax:
min(t) #t tuples
returns minimum value among the given tuple.
Example
>>> T=(100,200,300,400,500)
>>> min(T)
100
tuple( )
It is used to create empty tuple.
Syntax:
T=tuple() #t tuples
Create empty tuple.
Example
>>> t=tuple()
>>> print t
()
253
Solved Examples
1. Write a program to input 5 subject names and put it in tuple and display that tuple
information on the output screen.
Code
t=tuple()
for i in range(5):
a=raw_input("enter subject")
t=t+(a,)
print t
Output
>>>
enter subjectEnglish
enter subjectHindi
enter subjectMaths
enter subjectScience
output is
>>>
2. Write a program to input any two tuples and interchange the tuple values.
Code
t1=tuple()
254
for i in range(n):
a=input("enter elements")
t1=t1+(a,)
t2=tuple()
for i in range(m):
a=input("enter elements")
t2=t2+(a,)
print t1
print t2
t1,t2=t2,t1
print t1
print t2
Output
>>>
enter elements100
enter elements200
enter elements300
enter elements10
255
enter elements20
enter elements30
enter elements40
First Tuple
Second Tuple
AFTER SWAPPING
First Tuple
Second Tuple
>>>
3. Write a program to input ‘n’ numbers and store it in a tuple and find maximum &
minimum values in the tuple.
Code
t=tuple()
for i in range(n):
a=input("enter elements")
t=t+(a,)
Output
>>>
256
enter elements40
enter elements50
enter elements10
maximum value= 50
minimum value= 10
>>>
T=(10,30,2,50,5,6,100,65)
print max(T)
print min(T)
Output
100
t=tuple()
t = t +(PYTHON,)
print t
print len(t)
t1=(10,20,30)
print len(t1)
Output
('PYTHON',)
257
EXERCISE
(i) t=(10,20,30,40,50)
print len(t)
(ii) t=('a','b','c','A','B')
max(t)
min(t)
(iii) T1=(10,20,30,40,50)
T2 =(10,20,30,40,50)
T3 =(100,200,300)
cmp(T1,T2)
cmp(T2,T3)
cmp(T3,T1)
(iv) t=tuple()
Len(t)
(v) T1=(10,20,30,40,50)
T2=(100,200,300)
T3=T1+T2
print T3
2. Write a program to input two set values and store it in tuples and also do the
comparison.
3. Write a program to input ‘n’ employees’ salary and find minimum & maximum
salary among ‘n’ employees.
t=tuple{}
258
n=input(Total number of values in tuple)
for i in range(n)
a=input("enter elements")
t=t+(a)
5. Write a program to input ‘n’ customers’ name and store it in tuple and display all
customers’ names on the output screen.
6. Write a program to input ‘n’ numbers and separate the tuple in the following
manner.
Example
T=(10,20,30,40,50,60)
T1 =(10,30,50)
T2=(20,40,60)
259
Computer Science - Class XI
CENTRAL BOARD OF SECONDARY EDUCATION
Shiksha Kendra, 2, Community Centre, Preet Vihar, Delhi-110 092 India