0% found this document useful (0 votes)
3 views19 pages

XII CS Python Revision Tour

Uploaded by

shadilnisar000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

XII CS Python Revision Tour

Uploaded by

shadilnisar000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Distribution of Marks

Periods
Unit No. Unit Name Marks
Theory Practical

1 Computer Systems and Organisation 10 10 10

Computational Thinking and Programming


2 45 80 60
-1

3 Society, Law, and Ethics 15 20 —

Total 70 110 70

PYTHON REVISION TOUR


ABOUT PYTHON:
1. Python is a high-level programming language developed by Guido Van Rossum. The language was
re e ed in Febru ry 1991 nd got it n me from BB comedy erie “Monty Python’ F ying
ircu ”.
2. It is an interpreted and platform independent language i.e. the same code can run on any operating
system.
3. It can be used to follow both procedural and object-oriented approaches to programming.
4. It is free to use and based on two programming languages: ABC language and Modula-3.
BASIC TERMS USED IN PYTHON:
1. Token / Lexical Unit: The smallest individual unit in a python program is known as Token or Lexical
Unit. A token has a specific meaning for a python interpreter. Examples of tokens are: Keywords,
Identifiers, Literals, Operators and Punctuators.

5
2. Keywords: Keywords are the reserved words and have special meaning for Python Interpreters.
Each keyword can be used only for that purpose which it has been assigned. Examples: and, while, del,
with, True, None, False, return, try etc.
3. Identifiers: These are the names given to variables, objects, classes or functions etc. there are some
predefined rules for forming identifiers which should be followed else the program will raise Syntax
Error.
4. Literals: The data items that have a fixed value are called Literals. If a data item holds numeric
values it will be known as Numeric Literal, if it contains String values it will be known as String Literal
and so on. It means the type of value stored by the data item will decide the type of Literal. Python has
one special literal which is None to indicate absence of value.
5. Operators: These are the symbols that perform specific operations on some variables. Operators
operate on operands. Some operators require two operands and some require only one operand to
operate. The operator precedence in Python is as follows:

NOTE: When we compare two variables pointing to same value, then both Equality (==) and identity
(is) will return True. But when same value is assigned to different objects, then == operator will return
True and is operator will return False.
6. Punctuators: These are the symbols that are used to organize sentence structure in programming
ngu ge . ommon punctu tor re ‘ ‘’ # $ @ [] {} = ; () , .
7. Variables: In Python, variables are not storage containers like other programming languages. These
are the temporary memory locations used to store values which will be used in the program further.
Each time we assign a new value to a variable it will point to a new memory location where the
assigned value is stored. In Python we do not specify the size and type of variable, besides these are
decided as per the value we assign to that variable.
8. Data Type: It specifies the type of data we will store in the variable according to which memory will
be allocated to that variable and it will also specify the type of operations that can be performed on
that variable. Examples: integer, string, float, list etc.

6
9. Dynamic Typing: It means that it will be decided at the run time that which type of value the
variable will store. It is also called implicit conversion. For example,

Here, we need not to specify the type of value a will store besides we can assign any type of value to a
directly. Similarly, the data type of c will be decided at run time on the basis of value of a and b.
10. Type Casting: In Type casting, the data type conversion of a variable is done explicitly by using
some built-in functions. Here, we can say that we force the variable by applying a built-in function to
change the data type and it is not done at run time. Some common type casting functions are int(),
float(), str(), list(), tuple(), dict() etc.

DATA TYPES IN PYTHON:


Data types are classified in two basic categories: Mutable data types and Immutable data types.
Mutable data types are those data types whose value can be changed without creating a new object. It
means mutable data types hold a specific memory location and changes are made directly to that
memory location. Immutable data types are those data types whose value cannot be changed after
they are created. It means that if we make any change in the immutable data object then it will be
assigned a new memory location.
1. In Numeric data types, Integers allow storing whole numbers only which can be positive or negative.
Floating point numbers are used for storing numbers having fractional parts like temperature, area etc.
In Python, Floating point numbers represent double precision i.e. 15-digit precision. Complex numbers
are stored in python in the form of A + Bj where A is the real part and B is the imaginary part of
complex numbers.

7
2. Dictionary is an unordered set of commas separated values where each value is a key: value pair.
We represent the dictionary using curly brackets {}. Keys in the dictionary should be unique and they
cannot be changed while values of the keys can be changed.
3. Boolean allows storing only two values True and False where True means 1 and False means 0
internally.
4. Sequence data types store a collection or set of values in an ordered manner. We can traverse the
values/elements using indexing.
The sequence data types are:
A. STRING:
Introduction: String is a sequence which is made up of one or more UNICODE characters. Here the
character can be a letter, digit, whitespace or any other symbol. A string can be created by enclosing
one or more characters in single, double or triple quote.
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
Indexing: Each individual character in a string can be accessed using a technique called indexing. The
index specifies the character to be accessed in the string and is written in square brackets ([ ]). The
index of the first character (from left) in the string is 0 and the last character is n-1 where n is the
length of the string.

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

8
(iii) Membership: Python has two membership operators 'in' and 'not in'. The 'in' operator takes two
strings and returns True if the first string appears as a substring in the second string, otherwise it
returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' not in str1
False
(iv) Slicing: In Python, to access some part of a string or substring, we use a method called slicing. This
can be done by specifying an index range. Given a string str1, the slice operation str1[n:m] returns the
part of the string str1 starting from index n (inclusive) and ending at m (exclusive). In other words, we
can say that str1[n:m] returns all the characters starting from str1[n] till str1[m-1]. The numbers of
characters in the substring will always be equal to difference of two indices m and n,
i.e., (m-n).
>>> str1 = 'Hello World!'
>>> str1[1:5] #gives substring starting from index 1 to 4
'ello'
>>> str1[7:10] #gives substring starting from 7 to 9
'orl'
>>> str1[3:20] #index that is too big is truncated down to the end of the string
'lo World!'
>>> str1[7:2] #first index > second index results in an empty '' string
(v) Traversing a string using loops: We can access each character of a string or traverse a string using
for loop and while loop.
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch)
H
e
l
l
o

W
o
r
l
d
!

In the above code, the loop starts from the first character of the string str1 and automatically ends
when the last character is accessed.
(B) String Traversal Using while Loop:

9
>>> str1 = 'Hello World!'
>>> index = 0 #len(): a function to get length of string
>>> while index < len(str1):
print(str1[index], end = '')
index += 1
Hello World! #output of while loop
Here while loop runs till the condition index < len(str) is True, where index varies from 0 to len(str1) -1.
(vi) built-in functions:
i. len() : Returns the length of the given string.
>>> str1 = 'Hello World!'
>>> len(str1)
12
ii. title(): Returns the string with first letter of every word in the string in uppercase and rest in
lowercase.
>>> str1 = 'hello WORLD!'
>>> [Link]()
'Hello World!'
iii. lower(): Returns the string with all uppercase letters converted to lowercase
>>> str1 = 'hello WORLD!'
>>> [Link]()
'hello world!'
iv. upper(): Returns the string with all lowercase letters converted to uppercase
>>> str1 = 'hello WORLD!'
>>> [Link]()
'HELLO WORLD!'
v. count(str, start, end): Returns number of times substring str occurs in the given string. If we do not
give start index and end index then searching starts from index 0 and ends at length of the string.
>>> str1 = 'Hello World! Hello Hello'
>>> [Link]('Hello',12,25)
2
>>> [Link]('Hello')
3
vi. find(str,start, end): Returns the first occurrence of index of substring str occurring in the given
string. If we do not give start and end then searching starts from index 0 and ends at length of the
string. If the substring is not present in the given string, then the function returns -1.

>>> str1 = 'Hello World! Hello Hello'


>>> [Link]('Hello',10,20)
13
>>> [Link]('Hello',15,25)
19
>>> [Link]('Hello')
0
>>> [Link]('Hee')
-1
10
vii. index(str, start, end): Same as find() but raises an exception if the substring is not present in the
given string.
>>> str1 = 'Hello World! Hello Hello'
>>> [Link]('Hello')
0
>>> [Link]('Hee')
ValueError: substring not found

viii. endswith(): Returns True if the given string ends with the supplied substring otherwise returns
False.
>>> str1 = 'Hello World!'
>>> [Link]('World!')
True
>>> [Link]('!')
True
>>> [Link]('lde')
False
ix. startswith(): Returns True if the given string starts with the supplied substring otherwise returns
False
>>> str1 = 'Hello World!'
>>> [Link]('He')
True
>>> [Link]('Hee')
False
x. isalnum(): Returns True if characters of the given string are either alphabets or numeric. If
whitespace or special symbols are part of the given string or the string is empty it returns False.
>>> str1 = 'HelloWorld'
>>> [Link]()
True
>>> str1 = 'HelloWorld2'
>>> [Link]()
True
>>> str1 = 'HelloWorld!!'
>>> [Link]()
False
xi. islower(): Returns True if the string is non-empty and has all lowercase alphabets, or has at least
one character as lowercase alphabet and rest are non-alphabet characters
>>> str1 = 'hello world!'
>>> [Link]()
True
>>> str1 = 'hello 1234'
>>> [Link]()
True
>>> str1 = 'hello ??'
>>> [Link]()
True
>>> str1 = '1234'
>>> [Link]()
False
>>> str1 = 'Hello World!'
>>> [Link]()
False

11
xii. isupper(): Returns True if the string is non-empty and has all uppercase alphabets, or has at least
one character as uppercase character and rest are non-alphabet characters
>>> str1 = 'HELLO WORLD!'
>>> [Link]()
True
>>> str1 = 'HELLO 1234'
>>> [Link]()
True
>>> str1 = 'HELLO ??'
>>> [Link]()
True
>>> str1 = '1234'
>>> [Link]()
False
>>> str1 = 'Hello World!'
>>> [Link]()
False
xiii. isspace(): Returns True if the string is non-empty and all characters are white spaces (blank, tab,
newline, carriage return)
>>> str1 = ' \n \t \r'
>>> [Link]()
True
>>> str1 = 'Hello \n'
>>> [Link]()
False
xiv. istitle(): Returns True if the string is non-empty and title case, i.e., the first letter of every word in
the string in uppercase and rest in lowercase.
>>> str1 = 'Hello World!'
>>> [Link]()
True
>>> str1 = 'hello World!'
>>> [Link]()
False

xv. lstrip(): Returns the string after removing the spaces only on the left of the string
>>> str1 = ' Hello World! '
>>> [Link]()
'Hello World! '

xvi. rstrip(): Returns the string after removing the spaces only on the right of the string
>>> str1 = ' Hello World!'
>>> [Link]()
' Hello World!'
xvii. strip(): Returns the string after removing the spaces both on the left and the right of the string
>>> str1 = ' Hello World!'
>>> [Link]()
'Hello World!'

xviii. replace(oldstr, newstr): Replaces all occurrences of old string with the new string >>> str1 = 'Hello
World!'
>>> [Link]('o','*')
'Hell* W*rld!'

12
>>> str1 = 'Hello World!'
>>> [Link]('World','Country')
'Hello Country!'
>>> str1 = 'Hello World! Hello'
>>> [Link]('Hello','Bye')
'Bye World! Bye'
xix. join(): Returns a string in which the characters in the string have been joined by a separator
>>> str1 = ('HelloWorld!')
>>> str2 = '-' #separator
>>> [Link](str1)
'H-e-l-l-o-W-o-r-l-d-!'
xx. partition()): Partitions the given string at the first occurrence of the substring (separator) and
returns the string partitioned into three parts.
1. Substring before the separator
2. Separator
3. Substring after the separator If the separator is not found in the string, it returns the whole string
itself and two empty strings
>>> str1 = 'India is a Great Country'
>>> [Link]('is')
('India ', 'is', ' a Great Country')
>>> [Link]('are')
('India is a Great Country',' ',' ')

xxi. split(): Returns a list of words delimited by the specified substring. If no delimiter is given then
words are separated by space.
>>> str1 = 'India is a Great Country'
>>> [Link]()
['India','is','a','Great', 'Country']
>>> str1 = 'India is a Great Country'
>>> [Link]('a')
['Indi', ' is ', ' Gre', 't Country']

SUMMARY
• A string is a sequence of characters enclosed in single, double or triple quotes.
• Indexing is used for accessing individual characters within a string.
• The first character has the index 0 and the last character has the index n-1 where n is the length of
the string. The negative indexing ranges from -n to -1.
• Strings in Python are immutable, i.e., a string cannot be changed after it is created.
• Membership operator in takes two strings and returns True if the first string appears as a substring
in the econd e e return F e. Member hip oper tor ‘not in’ doe the reverse.
• Retrieving a portion of a string is called slicing. This can be done by specifying an index range.
• The slice operation str1[n:m] returns the part of the string str1 starting from index n (inclusive) and
ending at m (exclusive).
• Each character of a string can be accessed either using a for loop or while loop.
• There are many built-in functions for working with strings in Python.

13
B. LIST:
Introduction:
The data type list is an ordered sequence which is mutable and made up of one or more elements.
Unlike a string which consists of only characters, a list can have elements of different data types,
such as integer, float, string, tuple or even another list. A list is very useful to group together
elements of mixed data types. Elements of a list are enclosed in square brackets and are separated
by comma. Like string indices, list indices also start from 0.
Indexing: The elements of a list are accessed in the same way as characters are accessed in a string.
List operations (concatenation, repetition, membership & slicing):
Concatenation
Python allows us to join two or more lists using concatenation operator depicted by the symbol +.
>>> list1 = [1,3,5,7,9] #list1 is list of first five odd integers
>>> list2 = [2,4,6,8,10] #list2 is list of first five even integers
>>> list1 + list2 #elements of list1 followed by list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4
['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']
Repetition
Python allows us to replicate a list using repetition operator depicted by symbol *.
>>> list1 = ['Hello'] #elements of list1 repeated 4 times
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
Membership
Like strings, the membership operators in checks if the element is present in the list and returns
True, else returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False
Slicing
Like strings, the slicing operation can also be applied to lists.
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
Traversing a list using loops:
We can access each element of the list or traverse a list using a for loop or a while loop.
(A) List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Red
Green
Blue
Yellow
Black

14
Built-in functions:
i. len(): Returns the length of the list passed as the argument. Creates a list if a sequence is passed as
an argument
>>> list1 = [10,20,30,40,50]
>>> len(list1)
5
ii. list(): Creates an empty list if no argument is passed
>>> list1 = list()
>>> list1
[]
>>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']

iii. append(): Appends a single element passed as an argument at the end of the list The single
element can also be a list
>>> list1 = [10,20,30,40]
>>> [Link](50)
>>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40]
>>> [Link]([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]]
iv. extend(): Appends each element of the list passed as argument to the end of the given list
>>> list1 = [10,20,30]
>>> list2 = [40,50]
>>> [Link](list2)
>>> list1
[10, 20, 30, 40, 50]
v. insert(): Inserts an element at a particular index in the list
>>> list1 = [10,20,30,40,50]
>>> [Link](2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> [Link](0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]

vi. count(): Returns the number of times a given element appears in the list
>>> list1 = [10,20,30,10,40,10]
>>> [Link](10)
3
>>> [Link](90)
0
vii. index(): Returns index of the first occurrence of the element in the list. If the element is not
present, ValueError is generated
>>> list1 = [10,20,30,20,40,10]
>>> [Link](20)
1
>>> [Link](90)
ValueError: 90 is not in list
viii. remove(): Removes the given element from the list. If the element is present multiple times, only
the first occurrence is removed. If the element is not present, then ValueError is generated

15
>>> list1 = [10,20,30,40,50,30]
>>> [Link](30)
>>> list1
[10, 20, 40, 50, 30]
>>> [Link](90)
ValueError:[Link](x):x not in list
ix. pop(): Returns the element whose index is passed as parameter to this function and also removes it
from the list. If no parameter is given, then it returns and removes the last element of the list
>>> list1 = [10,20,30,40,50,60]
>>> [Link](3)
40
>>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> [Link]()
60
>>> list1
[10, 20, 30, 40, 50]
x. reverse(): Reverses the order of elements in the given list
>>> list1 = [34,66,12,89,28,99]
>>> [Link]()
>>> list1
[ 99, 28, 89, 12, 66, 34]
>>> list1 = [ 'Tiger' ,'Zebra' , 'Lion' , 'Cat' ,'Elephant' ,'Dog']
>>> [Link]()
>>> list1
['Dog', 'Elephant', 'Cat', 'Lion', 'Zebra', 'Tiger']
xi. sort(): Sorts the elements of the given list in-place
>>> list1 = ['Tiger', 'Zebra', 'Lion', 'Cat', 'Elephant', 'Dog']
>>> [Link]()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra']
>>> list1 = [34,66,12,89,28,99]
>>> [Link](reverse = True)
>>> list1
[99,89,66,34,28,12]
xii. sorted(): It takes a list as parameter and creates a new list consisting of the same elements
arranged in sorted order
>>> list1 = [23,45,11,67,85,56]
>>> list2 = sorted(list1)
>>> list1
[23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]
xiii. min() / max() / sum(): Returns smallest / largest / sum of elements of the list
>>> list1 = [34,12,63,39,92,44]
>>> min(list1)
12
>>> max(list1)
92
>>> sum(list1)
284

16
SUMMARY
Lists are mutable sequences in Python, i.e., we can change the elements of the list.

• E ement of i t re put in qu re br cket ep r ted by comm .


• A i t within i t i c ed ne ted i t. Li t indexing is same as that of strings and starts at 0. Two-
way indexing allows traversing the list in the forward as well as in the backward direction.
• Oper tor + conc ten te one i t to the end of nother i t.
• Oper tor * repe t i t by pecified number of time .
• Member hip oper tor in te if n e ement i pre ent in the i t or not nd not in does the
opposite.
• S icing i u ed to extr ct p rt of the i t.
• There re m ny i t m nipu tion function
including: len(), list(), append(), extend(), insert(), count(), find(), remove(), pop(), reverse(),
sort(), sorted(), min(), max(), sum().
C. TUPLE:
Introduction:
A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list
or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets) and are separated
by commas. Like list and string, elements of a tuple can be accessed using index values, starting
from 0.
Indexing:
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
Tuple is Immutable:
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it
has been created. An attempt to do this would lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment

Tuple operations:
Concatenation
Python allows us to join tuples using concatenation operator depicted by symbol +. We can also
create a new tuple which contains the result of this concatenation operation.
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2 #concatenates two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

Repetition
Repetition operation is depicted by the symbol *. It is used to repeat elements of a tuple. We can
repeat the tuple elements. The repetition operator requires the first operand to be a tuple and the
second operand to be an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

17
Membership
The in operator checks if the element is present in the tuple and returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True
Slicing
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80)

Built-in functions: len(), tuple(), count(), index(), sorted(), min(), max(), sum() work same as list.
SUMMARY
• Tuples are immutable sequences, i.e., we cannot change the elements of a tuple once it is
created.
• Elements of a tuple are put in round brackets separated by commas.
• If a sequence has comma separated elements without parentheses, it is also treated as a tuple.
• Tuples are ordered sequences as each element has a fixed position.
• Indexing is used to access the elements of the tuple; two-way indexing holds in dictionaries as in
strings and lists.
• Oper tor ‘+’ dd one equence ( tring, i t, tup e) to the end of other.
• Oper tor ‘*’ repe t equence ( tring, i t, tup e) by pecified number of time
• Member hip oper tor ‘in’ te if n e ement i pre ent in the equence or not nd ‘not in’ doe
the opposite.
• Tuple manipulation functions are: len(), tuple(), count(), index(), sorted(), min(), max(),sum().
D. Dictionary:
Introduction:
The data type dictionary falls under mapping. It is a mapping between a set of keys and a set of
values. The key-value pair is called an item. A key is separated from its value by a colon (:) and
consecutive items are separated by commas. Items in dictionaries are unordered, so we may not
get back the data in the same order in which we had entered the data initially in the dictionary.

Creating a Dictionary
To create a dictionary, the items entered are separated by commas and enclosed in curly braces.
Each item is a key value pair, separated through colon (:). The keys in the dictionary must be unique
and should be of any immutable data type, i.e., number, string or tuple. The values can be repeated
and can be of any data type.
#dict1 is an empty Dictionary created
#curly braces are used for dictionary
>>> dict1 = {}
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Accessing items in a dictionary using keys:
We have already seen that the items of a sequence (string, list and tuple) are accessed using a
technique called indexing. The items of a dictionary are accessed via the keys rather than via their
relative positions or indices. Each key serves as the index and maps to a value. The following
example shows how a dictionary returns the value corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']
18
89
>>> dict3['Sangeeta']
85
#the key does not exist
>>> dict3['Shyam']
KeyError: 'Shyam'
Mutability of dictionary (adding a new item, modifying an existing item): Dictionaries are mutable
which implies that the contents of the dictionary can be changed after it has been created.
Adding a new item
We can add a new item to the dictionary as shown in the following example: >>>
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Meena': 78}
Modifying an Existing Item
The existing dictionary can be modified by just overwriting the key-value pair.
Example to modify a given item in the dictionary:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
#Change marks of Suhel to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,'Sangeeta': 85}
Membership
The membership operator in checks if the key is present in the dictionary and returns True, else it
returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' in dict1
True
The not in operator returns True if the key is not present in the dictionary, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' not in dict1
False
Traversing a dictionary:
We can access each item of the dictionary or traverse a dictionary using for loop.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
Method 1
>>> for key in dict1:
print(key,':',dict1[key])
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Method 2
>>> for key,value in [Link]():
print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
19
Built-in functions: len(), dict(), keys(), values(), items(), get(), update(), del, clear(), fromkeys(),
copy(), pop(), popitem(), setdefault(), max(), min(), count(), sorted(), copy();

Method Description Example

len() Returns the length or >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,


number of key: value pairs Sangeeta':85}
of the dictionary passed as >>> len(dict1)
the argument 4

dict() Creates a dictionary from a pair1 =


sequence of key-value pairs [('Mohan',95),('Ram',89), ('Suhel',92),('Sangeeta',85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan':95, 'Ram':89,'Suhel':92,'Sangeeta': 85}

keys() Returns a list of keys in >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,


the dictionary 'Sangeeta':85}
>>> [Link]()
dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta'])

values() Returns a list of values in >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,


the dictionary 'Sangeeta':85}
>>> [Link]()
dict_values([95, 89, 92, 85])

items() Returns a list of tuples (key – >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
value) pair 'Sangeeta':85}
>>> [Link]()
dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92),
('Sangeeta', 85)])

get() Returns the >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,


value corresponding to the 'Sangeeta':85}
key passed as the argument >>> [Link]('Sangeeta')
If the key is not present in 85
the dictionary it will return >>> [Link]('Sohan')
None

update() appends the key-value pair >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
of the dictionary passed as 'Sangeeta':85}
the argument to the key- >>> dict2 = {'Sohan':79,'Geeta':89}
value pair of the given >>> [Link](dict2)
dictionary >>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85,
'Sohan': 79, 'Geeta':89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}

20
del() Deletes the item with >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
the given key to delete 'Sangeeta':85}
the dictionary from the >>> del dict1['Ram']
memory we write: >>> dict1
del Dict_name {'Mohan':95,'Suhel':92, 'Sangeeta': 85}
>>> del dict1 ['Mohan']
>>> dict1
{'Suhel': 92, 'Sangeeta': 85}
>>> del dict1
>>> dict1
NameError: name 'dict1' is not defined

clear() Deletes or clear all the >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,


items of the dictionary 'Sangeeta':85}
>>> [Link]()
>>> dict1
{}

• Diction ry i m pping (non-scalar) data type. It is an unordered collection of key value pair; key
value pair is put inside curly braces.
• E ch key i ep r ted from it v ue by co on.
• Key re unique nd ct the index.
• Key re of immut b e type but v ue c n be mut b e.

QUESTIONS:
1. What will be the output of the following expression?
float(5 + int(4.39 + 2.1) % 2)
a. 5.0 b. 5 c. 8.0 d. 8
2. What is the value of this expression?
3*1**3
a. 27 b. 9 c. 3 d. 1
3. What can be a possible output at the time of execution of the program from the following code?
import random
AR = [20,30,40,50,60,70];
FROM = [Link](1,3)
TO = [Link](2,4)
for K in range(FROM,TO+1):
print (AR[K],end=”# “)

(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#

4. Identify the invalid python statement from the following:


a. d = dict() b. l = {} c. f = () d. g = dict {}
5. List AL is defined as follows: AL = [1,2,3,4,5]
Which of the following statements removes the middle element 3 from it, so that list AL equals
[1,2,4,5]. (Multiple options are correct)
a. del a[2] b. a[2:3] = [] c. a[2:2] = [] d. a[2] = [] e. [Link](3)

6. Select the correct output of the following string operation.

21
tr1 = “W h ”
print( tr1[ 3] + “Bhyi” + tr1[-3:])
a. Wah Bhyi Wah b. Wah Bhyi aha c. WahBhyiWah d. WahBhyiWaha

7. Select the correct output of the following code:


event = “G Pre idency@ 3”
L = event. p it(“ “)
print(L[::-2])
a. [“G ”] b. G20 c. [“ s cy@2 2 ”] d. “Pre idency@ 3”

8. What is printed when the following code is executed?


K = [“R m”, “Shy m”, “Sit ”, “Git ”]
print(K[-1][-1])
a. R b. m c. Ram d. Gita e. a
9. What will be the output of the following code?
dict = {“Jo” 1, “R ” }
[Link] te({“Pho” })
print(dict)
a. {“J ”:1, “ ”:2, “ h ”:2} b. {“Jo” 1, “R ” }
c. {“Jo” 1, “Pho” } d. Error

10. What will be the output of the following Python code?


d1 = {‘ ’ 1 , ‘b’ , ‘c’ 3}
tr1 = ‘’
for i in d1:
str1 = str1 + tr(d1[i]) + ‘ ‘
str2 = str1[:-1]
print(str2[::-1])
a. 3, 2 b. 3, 2, 10 c. 3, 2, 01 d. Error
ASSERTION & REASON based questions.
1. Assertion (A): List is a mutable data type of Python.
Reason (R): In place change is not possible in list elements.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
2. Assertion (A): in and not in are called membership operators.
Reason (R): They return True based on the presence of a character/substring in a given string
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
3. Assertion (A): Python strings are mutable in nature.
Reason (R): Python strings are stored in memory by storing individual characters in contiguous
memory locations.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.

22
E - Both A and R are false.

4. Assertion (A): append() and extend() are both methods to insert elements in a list.
Reason (R): While append() adds elements at the end of the list, extend can add elements
anywhere in the list.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
5. Assertion (A): A dictionary cannot have two same keys with different values.
Reason (R): Keys of a dictionary must be unique.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
FILL IN THE BLANKS.
1. The ________ statement is an empty statement in Python.
pass
2. A _________ statement skips the rest of the loop and jumps over to the statement following the
loop.
break
3. Python's __________ cannot be used as variable name.
keywords
4. The explicit conversion of an operand to a specific type is called _________ .
type casting.
5. The data types whose values cannot be changed in place are called _________ types.
immutable
6. The _______ can add an element in the middle of a list.
insert()
7. The _________ only adds an element at the end of a list.
append()
8. The keys of a dictionary must be of ________ type.
immutable
9. Dictionary is an _________ set of elements.
unordered
10. To get all the keys of a dictionary, ________ method is used.
keys()

23

You might also like