1. REVISION TABLE OF STRING / LIST / TUPLE / DICTIONARY
CLASS XI SUB: COMPUTER SCIENCE
SUMAN VERMA , PGT(CS) , KV PITAMPURA
STRING LIST TUPLE DICTIONARY
DEFINITION
Characters enclosed in
single quotes, double quotes
or triple quotes (‘ ‘ , “ “ , ‘’’
‘’’) is called a string.
a standard data type of python
that can store a sequence of
values belonging to any type. It
is represented by []
Collection of same or
different type of data enclosed
in ()
It is an unordered collection of elements in the
form of key:value pair enclosed in {}.
Keys must be unique , values can be same.
Immutable
means str[i]=x Not possible
mutable sequence
means L[i]=x Is possible
Immutable
means t[i]=x Not
possible
Key is immutable and value is mutable
Indexing can be done indexing is possible Indexing can be done
Key acts as index to access value in the
dictionary
Example str='hello' , '123'
str="hello"
str='''hello'''
1) empty list ,L=list() or l=[]
2) nested
list,L1=[‘a’,’b’,[‘c’,’d’],’e’]
3) l=[1,2,'a','rohan']
1) empty tuple ,T=tuple() or
T=()
2) nested
tuple,T1=(‘a’,’b’,(‘c’,’d’),’e
’)
3) T=(1,2,'a','rohan')
Empty dictionary Emp = { } or Emp = dict( )
Nested dictionary-
Emp={'name':'rohan','addrs':{'HNo':20,'city':'Delhi'}}
String
creation
str=" hello I m string"
(initialized string)
l1=[1,2,'ram']
(initialized list)
T1=(1,2,'ram')
(initialized tuple)
DayofMonth= { “January”:31, ”February”:28,
”March”:31, ”April”:30, ”May”:31, ”June”:30,
”July”:31, ”August”:31, ”September”:30,
”October”:31, ”November”:30, ”December”:31}
(initialized dictionary)
str=input("enter string")
(from user)
l1= list(<any sequence>)
l1=eval(input(“enter list”))
L= [ ] and L.append(n)
T1= tuple(<any sequence>)
T1=eval(input(“enter tuple”))
T= () and use T=T+(n,)
Emp=dict(name=”rohan”,age=20,sal=1000)
d=eval(input(“enter dictionary”))
d={} and adding element by d[key]=value
2. String
Traversing
for ch in str:
print(ch)
TRAVERSING-
L=['p','y','t','h','o','n']
for a in L :
print(a)
TRAVERSING-
T=('p','y','t','h','o','n')
for a in T :
print(a)
TRAVERSING-
d={ “Table”:10, “Chair”:13, “Desk”:16, “Stool”:15, “Rack”:15 }
for k in d :
print( ‘Key is :’, k ,’ Value is: ’, d[k] )
for i in range(len(str)):
print("index:",i,"element is
::",str[i])
for reverse printing
for i in range(-1,-len(str)-1,-
1):
print("index:",i,"element
is ::",str[i])
for i in range(len(L1)):
print(L1[i])
ACCESSING- through index.
Eg:- L1=['L' , 'I' , 'S' ,'T']
>>>L1[0] #L
>>>L1[3] #T
>>>L1[-1] #T
>>>L1[-3] # I
for i in range(len(T1)):
print(T1[i])
ACCESSING- through index.
Eg:- T1=(‘T' , 'U' , 'P'
,'L',’E’)
>>>L1[0] #T
>>>L1[3] #L
>>>L1[-1] #E
>>>L1[-3] # P
d={ “Table”:10, “Chair”:13, “Desk”:16}
for k,v in d.items():
print(k,v)
Output-
Table 10
Chair 13
Desk 16
String
Operators
(join + ) and (replicate *)
S1=S2+S3 (“tea” + “pot”
= “teapot”)
S1=S2*3 (“go!” * 3 =
“go!go!go!”)
LIST OPERATORS-
1)joining- lst3=lst1+lst2
2)replicating-x=lst*3
3)slicing- seq=L[start:stop:step]
TUPLE OPERATORS-
1)joining- t3=t1+t2
2)replicating-x=t*3
3)slicing-
seq=T[start:stop:step]
3. Membershi
p
Operators
IN AND NOT IN - gives
True or False
“a” in “Sanjeev” will result
into True.
“ap” not in “Sanjeev” will
result into True
MEMBERSHIP OPERATOR-
IN and NOT IN-gives True or
False
'a' in ['a','b','c',] #true
'e' in ['a','b','c'] #false
'e' not in ['a','b'] #true
MEMBERSHIP
OPERATOR- IN and NOT
IN-gives True or False
'a' in ('a','b','c',) #true
'e' in ('a','b','c') #false
'e' not in ('a','b') #true
MEMBERSHIP OPERATOR- IN and NOT
d={ “Table”:10, “Chair”:13, “Desk”:16, “Stool”:15, “Rack”:15 }
'Table' in d gives True #Searching by key
10 in d.values() gives True # searching by value
Compariso
n
Operators
< , <=, >, >=, !=, = -
Gives True or False by
compairing ASCII values
•“a” == “a” True
• “abc”==“abc” True
• “a”!=“abc” True
• “A”==“a” False
• “abc” ==“Abc” False
• ‘a’<‘A’ False (because
Unicode value of lower
case is higher than upper
case)
COMPARISON
OPERATORS-
> , <, >=, <= are used.
[1,2,8,9]< [9,1] #true
[1,2,8,9] < [1,2,9,1] #true
[1,2,8,9]<[1,2,9,10] #true
[1,2,8,9]<[1,2,8,4] #false
COMPARISON
OPERATORS-
> , <, >=, <= are used.
(1,2,8,9)< (9,1) #true
(1,2,8,9) < (1,2,9,1) #true
(1,2,8,9)<(1,2,9,10) #true
(1,2,8,9)<(1,2,8,4) #false
String
Slicing
The process of extracting
some part of string
str[start:stop:step]
The process of extracting
some part of list
str[start:stop:step]
The process of
extracting some part of
tuple
str[start:stop:step]
PACKING- Creating tuple
from a set of values.
T=(12,23,45,67)
UNPACKING- Creating
individual values from tuple’s
elements. a,b,c,d=T
STRING
FUNCTIO
NS
len(str) len(lst)
x=len(t) len(d)
str.capitalize() list(sequence)
tuple(sequence) d=dict(key=value,key=value)
str.title() lst.index(item) X=min(t)
d.keys()
4. str.upper() lst.append(item) X=max(t)
d.values()
str.lower() lst1.extend(lst2)
X=sum(t) d.items()
str.count(substr) lst.insert(index ,item)
X=t.index(item) d.get(key)
str.find(substr) x=lst.pop(index)
X=t.count(item) d1.update(d2) Add or modify the values in d1
according to d2
str.index(substr) lst.remove(item)
t2=sorted(t1) - ascending
t2=sorted(t1 ,reverse=True) -
descending
del d[key]
str.isalnum()
lst.clear() delete all the items
only
del t2 will delete whole tuple
but del t2[i] will give error as
tuple is immutable
d. clear()
str.islower() lst.count(item)
d=dict.fromkeys(newkeys) to create dictionary with
new values
str.isupper() lst.reverse()
d2=d1.copy()
str.isspace()
lst.sort() /
lst.sort(reverse=True)
v=d.pop(key) return deleted value
k,v=d.popitem() return deleted key and value
str.isalpha()
Lst2=sorted(lst) - ascending
Lst2=sorted(lst ,reverse=True) -
descending
setdefault()-returns the value of the item with the
specified key.
If the key does not exist, insert the key, with the
specified value.
car = { "brand": "Ford", "model": "Mustang", "year":
1964}
x = car.setdefault("color", "white") # color added to car
x = car.setdefault("color") output=’White’ # value
returned
str.isdigit() X=min(lst)
X=max(d.keys())
X=max(d.values())
str.split() or
str.split(splitting char) X=max(lst)
X=min( d.values())
X=min(d.keys())
str.partition(partitioning
word)-gives tuple of head ,
partitioning word and tail)
X=sum(lst) X=count(d)
5. str.strip() remove leading
and trailing spaces
del lst[index] - to delete
single item
del lst[start:stop] - to delete
slice
del lst - to delete complete list
including structure
D1=sorted(d.keys())
D1=sorted(d.values())
D1=sorted(d.keys(),reverse=True) for descending
order
str.lstrip()
TO MAKE A COPY OF A
LIST-
a= [1,2,3]
b=list(a)
OR
import copy
l1=[2,5,7,8]
l2=copy.copy(l1)
print(l2)
output= [2,5,7,8]
d1={‘Name’:’Rohan’,’Marks’=100}
d2=d1.copy();
str.rstrip()
str.replace(old word,new
word)
PRACTIC
E
QUESTIO
NS
Write a program to input line(s) of
text from the user until enter is
pressed. Count the total number of
characters in the text (including
white spaces),total number of
alphabets, total number of digits,
total number of special symbols and
total number of words in the given
text. (Assume that each word is
separated by one space).
Write a program to check if a
number is present in the list or
not. If the number is present,
then print the position of the
number. Print an appropriate
message if the number is not
present in the list.
Write a program to input n
numbers from the user. Store
these numbers in a tuple. Print
the maximum and minimum
number from this tuple.
Write a program to enter names of employees
and their salaries as input and store them in a
dictionary.
Write a program to convert a string
with more than one word into title
case string where string is passed as
parameter. (Title case means that
the first letter of each word is
capitalised)
IMP CASE STUDY QN
The record of a student (Name,
Roll No., Marks in five subjects
and percentage of marks) is
stored in the following list:
stRecord = ['Raman','A-
36',[56,98,99,72,69], 78.8]
Write Python statements to
retrieve the following
Consider the following tuples,
tuple1 and tuple2:
tuple1 =
(23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the
following statements: 100,200
i. print(tuple1.index
(45)) =2
IMP CASE STUDY QN
Create a dictionary ‘ODD’ of odd numbers between 1
and 10, where the key is the decimal number
and the value is the corresponding number in words.
ODD={1:’ONE’,3:’THREE’, 5: ’FIVE’ , 7: ’SEVEN’ , 9:’NINE’}
Perform the following operations on this dictionary:
(a) Display the keys = ODD.KEYS()
(b) Display the values = ODD.VALUES()
6. information from the list
stRecord.
a) Percentage of the student
stRecord[3]
b) Marks in the fifth subject
=stRecord[2][4]
c) Maximum marks of the
student =max(stRecord[2])
d) Roll no. of the student =
stRecord[1]
e) Change the name of the
student from ‘Raman’ to
‘Raghav’
stRecord[0]=“Raghav”
ii. print(tuple1.count
(45)) = 3
iii. print(tuple1 +
tuple2)=
(23,1,45,67,45,9,5
5,45,100,200)
iv. print(len(tuple2))
=2
v. print(max(tuple1))
= 67
vi. print(min(tuple1))
= 1
vii. print(sum(tuple2))
= 300
viii. print(sorted(tuple
1,reverse=True) )
print(tuple1)
(c) Display the items = ODD.ITEMS()
(d) Find the length of the dictionary = LEN(ODD)
(e) Check if 7 is present or not = 7 IN ODD
(f) Check if 2 is present or not = 2 IN ODD
(g) Retrieve the value corresponding to the key 9
=ODD[9] OR ODD.GET[9]
(h) Delete the item from the dictionary
corresponding to the key 9 = DEL ODD[9]
Write a program which takes two
inputs one is a string and other is a
character. The program should
create a new string after deleting all
occurrences of the character from
the string and print the new string.
Consider the following list
myList. What will be the
elements of myList after the
following two operations:
myList = [10,20,30,40]
i. myList.append([50,60])
ANS- [10,20,30,40,[50,60]]
ii. myList.extend([80,90])
ANS-
[10,20,30,40,[50,60],80,90]
Write a program to read email
IDs of n number of students
and store them in a tuple.
Create two new tuples, one to
store only the usernames from
the email IDs and second to
store domain names from the
email ids. Print all three tuples
at the end of the program.
[Hint: You may use the
function split()]
IMP CASE STUDY QN
Write a program to input your friends’ names and
their Phone Numbers and store them in the
dictionary as the key-value pair. Perform the
following operations on the dictionary:
a) Display the name and phone number of all
your friends
a) Add a new key-value pair in this dictionary
and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of
names
4. Input a string having
some digits. Write a
function to return the sum
of digits present in this
string.
What will be the output of the
following code segment:
a. myList =
[1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
Write a program to input
names of n students and store
them in a tuple. Also, input a
name from the user and find if
this student is present in the
tuple or not.
Write a function to convert a number entered
by the user into its corresponding number in
words. For example, if the input is 876 then t
he output should be ‘Eight Seven Six’.
7. b. myList =
[1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
c) myList = [1,2,3,4,5,6,7,8,9,10]
del myList[::2]
print(myList)
5. Write a program that
takes a sentence as an input
parameter where each word
in the sentence is separated
by a space. The program
should replace each blank
with a hyphen and then
print the modified sentence.
What will be the output of the
following code segment:
myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
if i%2 == 0:
print(myList[i])
FROM CBSE SYLLABUS
Write a program to find the
maximum and minimum value
in the tuple entered by user.
FROM CBSE SYLLABUS
Write a program to create a dictionary with
names of employees and their salary and access
them.
Emp={‘Name’: [‘Sohan’,’Rohan’,’Vivek’],
’Salary’: [2000,3000,4000] }
OR
name=[]
sal=[]
Emp={‘Name’:name,’Salary’:sal}
Steps-
Input the total number of employees
Input name and salary and add in
the corresponding lists, Emp wll be automatically
updated
8. 1. Consider the following string
mySubject:
mySubject = "Computer
Science" What will
be the output of the following
string operations :
i.
print(mySubject[0:len(mySubjec
t)]) ii.
print(mySubject[-7:-1])
iii. print(mySubject[::2])
iv.
print(mySubject[len(mySubject)
-1]) v.
print(2*mySubject)
vi. print(mySubject[::-2])
vii. print(mySubject[:3] +
mySubject[3:]) viii.
print(mySubject.swapcase())
ix.
print(mySubject.startswith('Com
p')) x.
print(mySubject.isalpha())
Consider a list:
list1 = [6,7,8,9]
What is the difference between
the following operations on
list1:
a. list1 * 2
b. list1 *= 2
c. list1 = list1 * 2
FROM CBSE SYLLABUS
Write a program to find the
mean of values stored in a
tuple
Sum(tup)/len(tup)
Write a program to count the number of
times a character appears in a given string.
2. Consider the following string
myAddress: myAddress = "WZ-
1,New Ganga Nagar,New Delhi"
What will be the output of
following string operations :
i. print(myAddress.lower())
ii. print(myAddress.upper())
iii. print(myAddress.count('New'))
iv. print(myAddress.find('New'))
v. print(myAddress.rfind('New'))
vi. print(myAddress.split(','))
vii. print(myAddress.split(' '))
viii.
print(myAddress.replace('New','Old
'))
ix. print(myAddress.partition(','))
x. print(myAddress.index('Agra'))
Write a program to find the
number of times an element
occurs in the list.
FROM CBSE SYLLABUS
Write a program for counting
the frequency of elements in a
tuple and storing in a
dictionary.
Write a Python program to find the highest 2
values in a dictionary.
9. SOME PRACTICE
STATEMENTS >>> "hello how r u".split()
['hello', 'how', 'r', 'u']
Write a program to read a list of
n integers (positive as well as
negative). Create two new lists,
one having all positive numbers
and the other having all
negative numbers from the
given list. Print all three lists.
FROM CBSE SYLLABUS
Write a program to search an
element in the tuple using
LINEAR SEARCH.
>>> "hello,how,r,u".split(',')
['hello', 'how', 'r', 'u']
Write a program to read a list of
elements. Modify this list so
that it does not contain any
duplicate elements, i.e., all
elements occurring multiple
times in the list should appear
only once.
>>> "hello how,r,u".split(',')
['hello how', 'r', 'u']
Write a program to insert the
element at the desired position
in the list. Take the values of
element and position from the
user.
>>> "hello how r
u".partition('how')
('hello ', 'how', ' r u')
Write a program in python
which accepts a list Array of
numbers from user and swaps
the elements of 1st Half of the
list with the 2nd Half of the list
ONLY if the sum of 1st Half is
greater than 2nd Half of the list.
Sample Input Data of the list
Array= [ 100, 200, 300, 40, 50,
60],
Output Array = [40, 50, 60, 100,
200, 300]
>>> "hello how , r
u".partition(',')
('hello how ', ',', ' r u')
>>> "hello ,how ,r
u".partition(',')
('hello ', ',', 'how ,r u')