SlideShare ist ein Scribd-Unternehmen logo
1 von 10
Downloaden Sie, um offline zu lesen
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
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]
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()
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)
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()
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’.
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
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.
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')
STRING LIST TUPLE DICTIONARY FILE.pdf

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Python Programming
Python Programming Python Programming
Python Programming
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
String in java
String in javaString in java
String in java
 
Namespaces
NamespacesNamespaces
Namespaces
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Mysql
MysqlMysql
Mysql
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Python
PythonPython
Python
 
Brute force-algorithm
Brute force-algorithmBrute force-algorithm
Brute force-algorithm
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming Strings
 
Strings in c
Strings in cStrings in c
Strings in c
 
Method overloading
Method overloadingMethod overloading
Method overloading
 

Ähnlich wie STRING LIST TUPLE DICTIONARY FILE.pdf

Ähnlich wie STRING LIST TUPLE DICTIONARY FILE.pdf (20)

Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdfupdated_tuple_in_python.pdf
updated_tuple_in_python.pdf
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python data type
Python data typePython data type
Python data type
 
Array assignment
Array assignmentArray assignment
Array assignment
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
 
The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 

Kürzlich hochgeladen (20)

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

STRING LIST TUPLE DICTIONARY FILE.pdf

  • 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')