[go: up one dir, main page]

0% found this document useful (0 votes)
5 views81 pages

Question Bank - All Sequences

This document covers a revision of Python topics from class XI, including identifiers, literals, data types, operators, and control flow statements. It provides examples of valid and invalid identifiers, operator precedence, and various types of loops and decision-making statements. Additionally, it discusses string manipulation, built-in string functions, and includes a series of questions for assessment.

Uploaded by

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

Question Bank - All Sequences

This document covers a revision of Python topics from class XI, including identifiers, literals, data types, operators, and control flow statements. It provides examples of valid and invalid identifiers, operator precedence, and various types of loops and decision-making statements. Additionally, it discusses string manipulation, built-in string functions, and includes a series of questions for assessment.

Uploaded by

AkshatMishra 8b
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 81

Unit -1 : Computational Thinking and Programming-2

Topic: Revision of python topics covered in class XI

KEY POINTS:
Introduction to Python
Python is an open source, object oriented HLL developed by Guido van Rossum in 1991
Tokens- smallest individual unit of a python program.
Keyword-Reserved word that can’t be used as an identifier
Identifiers-Names given to any variable, constant, function or module etc.

Classify the following into valid and invalid identifier

Mybook (ii) Break (iii) _DK (iv) My_book (v) PaidIntrest (vi) s-num (vii)percent (viii) 123
(ix) dit km (x) class

Ans:(i)valid(ii)Invalid (iii)Valid (iv)valid (v)valid (vi)invalid (‘-‘)is not allowed


(vii)valid(viii)invalid(First Character must be alphabet(ix)invalid (no space is allowed)
(x)invalid (class is a keyword)

Literals- A fixed numeric or non-numeric value.


Variable- A variable is like a container that stores values to be used in program.
String- The text enclosed in quotes.
Comment- Comments are non-executable statement begin with # sign.
Docstring-Comments enclosed in triple quotes (single or double).
Operator – performs some action on data
o Arithmetic(+,-,*,/,%,**,//)
Relational/comparison (<,>, <=,>=, = =, !=).
o Assignment-(=,/=,+=,-=,*=,%=,**=,//=)
Logical – and, or
Membership – in, not in
Precedence of operators:
( ) Parentheses Highes
t
** Exponentiation
~ x Bitwise nor
+x, -x Positive, Negative (Unary +, -)
*(multiply), / (divide),//(floor division), %(modulus)
+(add),-(subtract)
& Bitwise and
^ Bitwise XOR
| Bitwise OR
<(less than),<=(less than or equal),>(greater than), >=(greater
than or
equal to), ==(equal),!=(not equal)
is , is not
not x Boolean NOT
and Boolean AND
or Boolean OR

Low
Important questions based on precedence of operators:

Data type:
There are following basic types of variable in as explained in last chapter:
Type Description
bool Stores either value True or False.
int Stores whole number.
float Stores numbers with fractional part.
Complex Stores a number having real and imaginary part
(a+bj)
String Stores text enclosed in single or double quote
List Stores list of comma separated values of any data
type between square [ ] brackets.(mutable )
Tuple Stores list of comma separated values of any data
type between parentheses ( ) (immutable)
Dictionary Unordered set of comma-separated key:value pairs ,
within braces {}
All questions are of 1 mark.
Q.No. Question
1. Which of the following is a valid identifier:
i. 9type ii._type iii. Same-type iv. True
2. Which of the following is a relational operator:
i. > ii. // iii. or iv. **
3. Which of the following is a logical operator:
i. + ii. /= iii. and iv. in
4. Identify the membership operator from the following:
i. in ii. not in iii. both i & ii iv. Only i
5. Which one is a arithmetic operator:
i. not ii. ** iii. both i & ii iv. Only ii
6. What will be the correct output of the statement :
>>>4//3.0
i. 1 ii. 1.0 iii 1.3333 iv. None of the above
7. What will be the correct output of the statement : >>>
4+2**2*10
i. 18 ii. 80 iii. 44 iv. None of the above
8. Give the output of the following code:
>>> a,b=4,2
>>> a+b**2*10
i. 44 ii. 48 iii. 40 iv.88
9. Give the output of the following code:
>>> a,b = 4,2.5
>>> a-b//2**2
i. 4.0 ii. 4 iii. 0 iv. None of the above
10. Give the output of the following code:
>>>a,b,c=1,2,3
>>> a//b**c+a-c*a
i.-2 ii. -2.0 iii. 2.0 iv. None of the above
11. If a=1,b=2 and c= 3 then which statement will give the
output as : 2.0 from the following:
i. >>>a%b%c+1 ii. >>>a%b%c+1.0 iii.
>>>a%b%c iv. a%b%c-1
12. Which statement will give the output as : True from the
following :
i.>>>not -5 ii. >>>not 5 iii. >>>not 0 iv. >>>not(5-1)
13. Give the output of the following code:
>>>7*(8/(5//2))
i. 28 ii. 28.0 iii. 20 iv. 60
14. Give the output of the following code:
>>>import math
>>> math.ceil(1.03)+math.floor(1.03)
i. 3 ii. -3.0 iii. 3.0 iv. None of the above
15. What will be the output of the following code:
>>>import math
>>>math.fabs(-5.03)
i. 5.0 ii. 5.03 iii. -5.03 iv . None of the above
Single line comments in python begin with… symbol.
16. i. # ii. “ iii. % iv. _
17. Which of the following are the fundamental building block
of a python program.
i. Identifier ii. Constant iii. Punctuators iv.
Tokens
18. The input() function always returns a value of type.
i. Integer ii.float iii.String iv.Complex
19. ……….. function is used to determine the data type of a
variable.
i. type( ) ii. id( ) iii. print( ) iv. str( )
20. The smallest individual unit in a program is known as
a……………
i. Token ii.keyword iii. Punctuator iv. identifier
FLOW OF EXECUTION
#Decision making statements in python
Description
Statement
if statement An if statement consists of a boolean
expression followed by one or more
statements.
An if statement can be followed by an
if...else statement optional else statement, which executes
when the boolean expression is false.
If the first boolean expression is false, the
if…elif…else next is checked and so on. If one of the
condition is true , the corresponding
statement(s) executes, and the statement
ends.
It allows to check for multiple test expression
nested if…else and execute different codes for more than
statements two conditions.

#Iteration or Looping construct statements in python

Description
Loop
for loop:
for<ctrl_var>in<sequence It is used to iterate/repeat ifself over a range
>: of values or sequence one by one.
<statement in loop body>
else:
<statement>
while loop:
while<test_exp>: body of The while loop repeatedly executes the set
while else: of statement till the defined condition is
body of else true.
21. Which of the following is not a decision making statement
i. if..else statement ii. for statement iii. if-elif statement iv.ifstatement
22. …………loop is the best choice when the number of iterations are known.
i. while ii. do-whileiii. for iv. None of these
23. How many times will the following code be executed.

a=5
while a>0: print(a)
print(“Bye”)

i. 5 times ii. Once iii. Infinite iv. None of these


24. What abandons the current iteration of the loop
i. continue ii. stop iii. infinite iv. Break
25. Find the output of the following python program
for i in range(1,15,4): print(i, end=’,’)

i. 1,20,3 ii. 2,3,4 iii. 1,5,10,14 iv. 1,5,9,13


26. …………loop is the best when the number of iterations are not known.
i. while ii. do-whileiii. for iv. None of these
27. In the nested loop loop must be terminated before the outer loop.
i. Outer ii. enclosing iii. Inner iv. None of these
28. …………..statement is an empty statement in python.
i. pass ii. break iii. Continue iv. if
29. How many times will the following code be executed
for i in range(1,15,5): print(i,end=’,’)

i.3 ii. 4 iii. 1 iv. infinite


30. Symbol used to end the if statement:
i. Semicolon(;) ii. Hyphen(-) iii. Underscore( _ ) iv. colon(:)

Ch- String Manipulation

String is a sequence of characters, which is enclosed between either single (' ') or double quotes (" “) and
triple (‘’’ ‘’’) quotes, python treats both single and double quotes same. Python strings are immutable. In
string each character has a unique index value. The indexes of a string begins from (0) to length-1 in forward
direction and-1, - 2,-3…-length in backward direction.
String operators:

1.String concatenation operator (+)


Eg: “Python” + “Notes” = PythonNotes
“123”+ “abc” = 123abc
‘2’ + 3 =Invalid ( It will produce error)
2.String Replication operator (*)
Eg: “a” * 3=”aaa”
4 * “$”=”$$$$”
‘2’ * ‘3’ =Invalid (It will produce error)
3.Membership operator (in , not in)
It returns the result in TRUE or FALSE
Eg: ‘y’ in ‘python’ =TRUE
O/P
‘y’ not in ‘python’=FALSE
True

False
True

‘th’ in ‘python’=TRUE
SOLVE:
S1=”computer”
S2=”computer_science”
S3=”python”
Print(S1 in S2)
Print(S2 in S1)
print(S3 not in S1)
print(S3 in S2)

4.Comparison Operators( all relational operators, <,<=,>,>=,==.!=)


Eg: “a”==”a”
True
“ABC”==”abc” False
‘0’<’1’ True
‘a’>’A’ True

Ordinal values
0 TO 9- 48 TO 57
A To Z- 65 TO 90
a to z- 97 to 122

String Slices:
It is a part of a string containing some contiguous characters from the string.
Eg:
0 1 2 3 4 5 6
a m a z i n g

Word -7 -6 -5 -4 -3 -2 -1

Word[0:7] “amazing”

Word[0:3] “ama”

Word[-7:-3] “amaz”

Word[:7] “amazing”
Word[3:] “zing”

Word[:3] + Word[3:] “amazing”

Word[1:6:2] “mzn”

Word[-7:-3:3] “az”

Word[::-2] “giaa”

Creating String

e.g.

a=‘Computer Science'

b=“Informatics Practices“

#Accessing String Elements . output


str='Computer Sciene'
('str-', 'Computer Sciene')

print('str-',str)

Iterating/Traversing through string

#Each character of the string can be accessed sequentially using for loop.
e.g.-str='Computer Sciene‘
for i in str:
print(i)
Updating Strings-String value can be updated by reassigning another value in it.

e.g. var1 = 'Comp Sc'

var1 = var1[:7] + ' with Python'

print ("Updated String :- ",var1 )

OUTPUT

('Updated String :- ', 'Comp Sc with Python')

BUILT IN FUNCTIONS –STRING


Function Description Eg: output
len() Returns the length s="hello world";print(len(s)) 11
of the string. s1='123';print(len(s1)) 3
s1=123;print(len(s1)) print(len(s1))
TypeError: object of type 'int' has
no len()
capitalize() Converts the first s="hello world welcome"
letter of the string print(s.capitalize()) Hello world welcome
in uppercase
split() Breaks up a string s="hello@ world@ wel@come"
at the specified print(s.split()) ['hello@', 'world@', 'wel@come']
separator and
print(s.split('@')) ['hello', ' world', ' wel', 'come']
returns a list of
substrings. print(s.split('@',2)) ['hello', ' world', ' wel@come']
print(s.split(';')) ['hello@ world@ wel@come']
#Return type:LIST
replace() It replaces all the s="hello@ world@ wel@come"
occurrences of the print(s.replace('@','#')) hello# world# wel#come
old string with the
print(s.replace('@','#',2)) hello# world# wel@come
new string.
print(s.replace('$','#')) hello@ world@ wel@come

find() It is used to search s="hello@ world@ wel@come"


the first occurrence print(s.find('@')) 5
of the substring in
print(s.find('@',7,15)) 12
the given string.
print(s.find('#')) -1
It also searches the s="hello@ world@ wel@come" 5
index()
first occurrence and print(s.index('@')) 12
returns the lowest print(s.index('@',7,15)) Value Error: substring not found
index of the print(s.index('#'))
substring.

Function Description Eg: output

It checks for print("hello".isalpha()) True


isalpha()
alphabets in an print("he123".isalpha()) False
inputted string and
print("he@#".isalpha()) False
returns True in
string contains only print("123".isalpha()) False
letters. print("hello world".isalpha()) False

isalnum() It returns True if all print("hello".isalnum()) True


the characters are print("he123".isalnum()) True
alphanumeric.
print("he@#".isalnum()) False
print("123".isalnum()) True
print("hello world".isalnum()) False
isdigit() It returns True if print("hello".isdigit()) False
the string contains print("he123".isdigit()) False
only digits.
print("he@#".isdigit()) False
print("123".isdigit()) True
print("hello world".isdigit()) False
It returns the string s="hello@ world@ wel@come" Hello@ World@ Wel@Come
title()
with first letter of print(s.title())
every word in the
string in uppercase
and rest in
lowercase.
count() It returns number s="hello@ world@ wel@come"
of times substring print(s.count('@')) 3
str occurs in the
print(s.count(' ')) 2
given string.
print(s.count('e')) 3
print(s.count('#')) 0
Function Description Eg: output
lower() It converts the print("HE123".lower()) he123
string into print("HE@#".lower()) he@#
lowercase
print("12".lower()) 12
print("Hello World".lower()) hello world
islower() It returns True if all print("he123".islower()) True
the letters in the print("he@#".islower()) True
string are in
print("12".islower()) False
lowercase.
print("Hello World".islower()) False
upper() It converts the print("he123".upper()) HE123
string into print("he@#".upper()) HE@#
uppercase
print("12".upper()) 12
print("Hello World".upper()) HELLO WORLD
isupper() It returns True if all print("hE123".isupper()) False
the letters in the print("HE@#".isupper()) True
string are in
print("12".isupper()) False
uppercase.
print("Hello World".isupper()) False
lstrip() It returns the string print("3hE123".lstrip('3')) hE123
after removing the print(" 3hE1 ".lstrip()) 3hE1
space from the left print("1245s".lstrip('124')) 5s
of the string print(" 1245".lstrip('124')) 1245
print("12 45".lstrip('124')) 45
rstrip() It returns the string print("3hE123".rstrip('3')) 3hE12
after removing the print("3hE1 ".rstrip()) 3hE1
space from the
print("1245s".rstrip('5s')) 124
right of the string
print("1245 ".rstrip('4')) 1245
print("124545".rstrip('45')) 12
It returns the print("3hE123".strip('3')) hE12
strip()
string after print(" 3hE1 ".strip()) 3hE1
removing
print("1245s".strip('5s')) 124
the space
from the print("41245 ".strip('4')) 1245
both side of print("124545".strip('45')) 12
the string
Function Description Eg: output

istitle() It returns True if print('hello@ world@'.istitle()) False


the string is print('hello@ World@'.istitle()) False
properly title-cased.
print('Hello@ World@'.istitle()) True
swapcase() It converts print('hEllo wOrlD@'.swapcase()) HeLLO WoRLd@
uppercase letter to
lowercase and vice
versa of the given
string.
join() It joins a string or print("*".join('hello')) h*e*l*l*o
character after each print("**".join(['hello','world'])) hello**world
member of the print("**".join(('hello','world'))) hello**world
string iterator. print("**".join('hello','world')) Error
partition() It splits the string at s="h@ello@ pyth@n world@"
the first occurance print(s.partition('@')) ('h', '@', 'ello@ pyth@n world@')
of separator and
print(s.partition(' ')) ('h@ello@', ' ', ' pyth@n world@')
returns a tuple.
Error
print(s.partition())
Startswith() Returns true if the print('abcd'.startswith('ab')) True
string starts with print(' abcd'.startswith('')) True
given substring
print('abcd'.startswith('cd')) False
endswith() Returns true if the print('abcd'.endswith('ab')) False
string ends with print('abcd '.endswith('')) True
given substring
print('abcd'.endswith('ab')) False

ord() It returns the print(ord('A')) 65


ASCII/Unicode of print(ord('Aa')) Error
the character.
It returns the print(chr(90)) Z
chr()
character print(chr(110)) n
represented
by the
imputed
Unicode
/ASCII
number
PRACTICE SHEET

Q.1 which of the following is not a Python legal string 4. ”Hello World”. Find(“Wor”)
operation? 5. ”Hello World”. Find(“wor”)
(a)‟abc‟ + ‟abc‟ (b) “abc‟*3 (c)‟abc‟ + 3 6. ”Hello World”.isalpha()
7. ”Hello World”.isalnum()
Q.2 Out of the following operators, which ones can be
8. ”Hello World”.isdigit()
used with strings?
Q5.Suggest appropriate functions for the following tasks
=, -, *, /, //, %, >, <>, in, not in, <= –

Q.3 From the string S = “CARPE DIEM”. Which ranges  To check whether the string

return “DIE” and “CAR”  To check the occurance of a string within another

Given a string S = “CARPE DIEM”. If n is length/2 then string.

what would be following return?  To check first letter of a string to upper case.

(a) S [: n] (b) S[n:] (c) S[n:n] (d) S [1:n]  To check whether all the letters of the string are in

(e) S[n: length-1] capital letters.

Q4. What would following expression return?  To remove all the white spaces from the beginning of a

1. HelloWorld”. Upper().lower() string.

2. ”Hello World”.lower().upper() Q6.Find the output-if input as ‘Hello’

3. ”HelloWorld”. Find(“Wor”,1,6)
strlen=len(str1)+5
print(strlen)
i.18 ii.19 iii.13 iv.15
Q7.WAP to check the given string is palindrome or not Eg. 2.Which method removes all the leading whitespaces from
NITIN Palindrome[rev] is: NITIN the left of the string.
Q8.WAP to print the number of occurances of a substring i.split() ii.remove() iii lstrip() iv rstrip()
into a line. 3.It returns True if the string contains only whitespace
Q9. WAP to count total no. of alphabets in string. characters, otherwise returns False.
Q10.WAP to print its statics like: i) isspace() ii.strip() iii. islower() iv. isupper()
i. No. of lowercase ii. No. of uppercase 4.It converts uppercase letter to lowercase and vice versa
iii.No. of digits iv.No. of spaces of the given string.
i. lstrip() ii.swapcase() iii.istitle() iv.count()
Q11.If the string is “SIPO” then display double each 5.What will be the output of the following code.
character. Str=’Hello World! Hello Hello’
Eg:SSIIPPOO Str.count(‘Hello’,12,25) i.2 ii.3 iii.4
iv.5
6.What will be the output of the following code.
Str=”123456”
MCQ
print(Str.isdigit()) i.True ii.False iii.None iv.Error
1 .What will be the output of the following code
7.What will be the output of the following code.
str1=”I love Python”
Str=”python 38” print(A.replace(‘Virtual’,’Augmented’))
print(Str.isalnum()) i. Virtual Augmented iii. Reality Augmented
i.True ii. False iii. None iv .Error ii. Augmented Virtual iv. Augmented Reality
8.What will be the output of the following code. 12.What will be the output of the following code?
Str=”pyThOn” print(“ComputerScience”.split(“er”,2))
print(Str.swapcase()) i. [“Computer”,”Science”] iii. [“Comput”,”Science”]
i.PYtHoN ii.pyThon iii.python iv.PYTHON ii.[“Comput”,”erScience”] iv.
9.What will be the output of the following code. [“Comput”,”er”,”Science”]
Str=”Computers” 13.Following set of commands are executed in shell, what
print(Str.rstrip(“rs”)) will be the output?
i.Computer iiComputers iii.Compute >>>str="hello"
iv.Compute >>>str[:2]
10.How many times is the word ‘Python’ printed in the i. he ii. lo iii. olleh iv. hello
FOLLOWING statement. 14.………..function will always return tuple of 3 elements.
S=’I Love Python’ i.index() ii.split() iii.partition() iv.strip()
for ch in S: 15.What is the correct python code to display the last four
print(‘Python’) characters of “Digital India”
i.11 times ii.8 times iii.3 times iv.5 times i. str[-4:] ii.str[4:] iii.str[*str] iv.str[/4:]
11.What will be the output of the following code?
A=”Virtual Reality”
Ch-List Manipulation
It is a collections of items and each item has its own index value.Index of first item is 0 and the last item is n-1.Here n is
number of items
in a list.
Creating a list
Lists are enclosed in square brackets [ ] and each item is separated by a comma.
e.g.
list1 = [‘English', ‘Hindi', 1997, 2000]
list2 = [11, 22, 33, 44, 55 ]
list3 = ["a", "b", "c", "d"]
list4=[] #empty list
Creating list from existing sequences or methods
Eg1:
L=list(1,2,3) Output:
Print(L) [1,2,3]

Eg2:
T=(1,2,3)
L=list(T)
Output:
Print(L)
Output
Eg3:
L=eval(input(“Enter values”)) Enter values [2,7,4,’a’,9]
Print(“List you eneterd”,l)

Eg4:
t= [(8,2,7,0),(7,4,4,3),"abc"]
print((t)) output
t[1]=56 [(8, 2, 7, 0), (7, 4, 4, 3), 'abc']
print(t)

Python Results Description


Expression

Length
len([4, 2, 3])
Concatenation
[4, 2, 3] + [1, 5, 6] [4, 2, 3, 1, 5, 6]
Repetition
[‘cs!'] * 4 ['cs!', 'cs!', 'cs!',
'cs!']
Membership
3 in [4, 2, 3] True
Iteration/Traversing
for x in [4,2,3] : 423
print (x,end = ' ')

Nested list: A nested list in python allows a list to contain multiple sublists within itself.
Each sublist can have items of different data types. It can be created by placing comma-
separated sublists and items together.

L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[2])
# Prints ['cc', 'dd', ['eee', 'fff']]

print(L[2][2])
# Prints ['eee', 'fff']

print(L[2][2][0])
# Prints eee

Slicing of A List

List elements can be accessed in subparts.


Eg: Output

['I', 'N', 'D']


list =['I','N','D','I','A']
print(list[0:3])
print(list[3:])
print(list[:])
print(list[::3])
print(list[0:5:2])
print(list[::-1])
print(list[1::2])
print(list[-5:4])

Comparison in List Sequences:


Comparison
Result
[1,2,8,9]<[9,1]
True
[1,2,8,9]>[1,2,9,10] False

To get as input a list from the user.


Eg: llst = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
val = int(input())
lst.append(val) # adding the element
print(lst)

Add Item to A List


Eg:

list=[1,2]
print('list before append', list)
list.append(3) # append() method is used to add an Item to a List.
print('list after append', list)
list.extend([4,5,6]) # extend() method is used to add multiple items in a list.
print(list)
Output

('list before append', [1, 2])

('list after append', [1, 2, 3])


[1, 2, 3, 4, 5, 6]

BUILT IN FUNCTIONS –LIST


Function Description Eg: output Error occur stt.
append() It adds a single s=['red','yellow','blue'] s.append['green']
item to the end s.append('green') ['red', 'yellow', 'blue', 'green']
of the list.
print(s) ['red', 'yellow', 'blue', 'green', s.
s. append(['white','black']) #nested list ['white', 'black']] append('white','black')
print(s)
extend() It adds one list at s=['red','yellow','blue'] ['red', 'yellow', 'blue', 'green', s.extend('green','white
the end of s.extend(['green','white']) 'white'] ')
another list
print(s)
insert() It adds an s=[1,3,4,5]
element at a s.insert(1,2) [1, 2, 3, 4, 5]
specified index.
print(s) [1, 2, 3, 4, 5, 'red']
s.insert(len(s),'red')
[1, 2, 3, 4, 5, 'blue', 'red']
print(s)
[1, 2, [1, 'white'], 3, 4, 5, 'blue', 'red']
s.insert(-1,'blue') # value inserted in -2
index.insert doesn’t add value in last index.
print(s)
s.insert(2,[1,'white'])
print(s)
reverse() It reverses the s=[1,3,4,5] [5, 4, 3, 1] Takes no argument
order of the s.reverse()
elements in a list.
print(s)
index() It returns the s=[1,2,3,4,5]
index of first print(s.index(4)) 3
matched item
print(s.index(12)) ValueError: 12 is not in list
from the list.
len() Returns the s=[1,2,3,4,5]
length of the list
i.e. number of
print(len(s)) 5
elements in a list
sort() This function s=[1,12,30,42,5]
sorts the items of s.sort() [1, 5, 12, 30, 42]
the list.
print(s)
[42, 30, 12, 5, 1]
s.sort(reverse=True)
print(s)
sorted() It takes the name s=[5,12,30,42,2] s.sorted(s) #error
of the list as an s=sorted(s) #assignment is must
argument and print(s) [2, 5, 12, 30, 42]
returns a new
s=sorted(s, reverse=True)
sorted list.
print(s) [42, 30, 12, 5, 2]
clear() It removes all the s=[1,12,30,42,5] Takes no argument
elements from s.clear() [] #returns empty list
the list.,the list
print(s)
objects still
exists as an
empty list.
del Delete all the list s=['a','e','i','o','u'] ['a', 'e', 'i', 'o', 'u']
elements from print(s)
memory
del(s) NameError: name 's' is not defined
print(s)
count() It counts how s=[12,12,30,42,12] Takes one argument
many times an print(s.count(12)) 3
element has 0
print(s.count(55))
occurred in a list
and returns it.
It removes the s=[5,12,30,42,2]
pop()
element from the s.pop() [5, 12, 30, 42]
end of the list or
print(s) [5, 12, 42]
from the
specified index s.pop(2)
and also returns print(s) IndexError: pop index out of range
it. s.pop(42)
Returns s=[5,12,30,42,2]
min(),
minimum ,maxi print(min(s)) 2
max(), mum and sum of
print(max(s)) 42
total only
sum() integer values print(sum(s)) 91

s=['a','e','i','o','u']
print(min(s)) a
print(max(s)) u
print(sum(s)) #error TypeError: unsupported operand
type(s) for +: 'int' and 'str'

PRACTICE SHEET-LIST
Q.1 Start with the list[8,9,10]. Do the following print(l[-3]) print(l)
using list functions
a) Set the second entry (index 1) to 17 2.l1=(1,3,5,7 4.l=[1,2,7,9] 7.l=[1,2,7,9
b) Add 4, 5 and 6 to the end of the list ,9) ]
a=list(l)
c) Remove the first entry from the list.
Print(l1==l1. a=l.copy()
d) Sort the list. a[1]=100
reverse())
e) Double the list. f) Insert 25 at index 3 a[1]=100
print(l)
Q2. If a is [1, 2, 3], what is the difference (if any) Print(l1)
between a*3 and [a, a, a]? print(l)
Q3.How are lists different from strings when both 3.l=[2,3,4,6] 5.>>> l=[2,6,7]
are sequences?
l=[1,2,3]
Q4.Differentiate between l.reverse() a=l
1. Pop() and remove() 3. Clear() and del >>>
2. Append() and extend() 4. Sort() and sorted() print(l) a.append([
l[3:]="hello"
Q5.Find the output: 20,30])
l.sort(revers
1. 6.l=[1,2,7,9 >>> print(l)
e=True) a.extend([4
,12,13] >>>l[10:20]=2 ,7])
L = ['a', 'b', ['cc', 'dd', ['eee', print(l)
'fff'], 'g', 'h'] l.pop() 00,300
print(l)
print(L[2]) print(l) >>> print(l)

print(L[2][2]) l.pop(2) >>> l[3:]=100

print(L[2][2][0]) print(l) Q6.Add 5 in every even value of a List


Eg: 'Original List', [12, 3, 48, 9, 10, 15, 18, 33, 1, 62]
print(L[0:2]) del l[0:2] updated List', [17, 3, 53, 9, 15, 15, 23, 33, 1, 67]
Q7.Add 2 in odd index value. L=[2,3,1,4,3,2]
Q8. l=[2,3,4,1,5,22,6,9,2,5,8,1,5,10,6]
Display sum of every third element of a list
Q9.. Delete all 2 from list l=[1,2,7,2,4,2,5,2]
Q10.WAP that displays options for inserting or deleting
element from
list as per user’s choice to be delete/add by value
or index.
Q11. WAP to find the frequencies of all elements of a
list. Also ,print the list of unique elements in the
given list.
Ch-Tuples
Tuples-It is a sequence of immutable (same or mix data type) objects. It is just like list. Difference
between the tuples and the lists is that the tuples cannot be changed unlike lists. Lists uses
square bracket where as tuples use parentheses.
Creating A Tuple

A tuple is enclosed in parentheses () for creation and each item is separated by a comma. e.g.
tup1 = (‘comp sc', ‘info practices', 2020, 2021)

tup2 = (5,11,22,44)
t=(1,) # created tuple for single element
Accessing Values from Tuples

Use the square brackets for slicing along with the index or indices to obtain the value available
at that index.
e.g.

tup1 = ("comp sc", "info practices", 2022, 2023)


tup2 = (5,11,22,44,9,66)
print ("tup1[0]: ", tup1[0]) OUTPUT:
print ("tup2[1:5]: ", tup2[1:5])

Iterating Through A Tuple

Element of the tuple can be accessed sequentially using loop.

e.g.

tup = (5,11,22)
Output
for i in range(0,len(tup)):

print(tup[i])
Updating Tuples

Tuples are immutable,that’s why we can’t change the content of tuple.It’s alternate way is to
take contents of existing tuple and create another tuple with these contents as well as new
content.

Concatenate tuple
t=(1,"abc",4.5) Output:
t=t+(2,3)
print(t)
(1, 'abc', 4.5, 2, 3)

Delete Tuple Elements

Direct deletion of tuple element is not possible but shifting of required content after discard of
unwanted content to another tuple.

e.g.
Output
tup1 = (1, 2,3)
tup3 = tup1[0:1] + tup1[2:]
print (tup3)
NOTE : Entire tuple can be deleted using del statement. e.g. del tup1

Comparing Tuples

(0,1,2) < (5,1,2) True


(0,2,20000) < (0,3,4) True
(‘Anmol’,’Kiran’) > (‘Riya’,Sneha’) False
Packing and Unpacking a Tuple : In Python there is a very powerful tuple assignment feature that
assigns right hand side of values into left hand side. In other way it is called unpacking of a tuple of
values into a variable. In packing, we put values into a new tuple while in unpacking we extract
those values into a single variable.

Eg1:
t=(1,"abc",4) Output:
x,y,z=t
1 abc 4
print(x,y,z)

Eg 2:
t=(1,"abc",4,5,7,9)
x,y,*z=t # All values will be assigned to every variable on left hand side and all remaining values
will be assigned to *args
print(x,y,z)
Output:
1 abc [4, 5, 7, 9]

Basic Tuples Operations


Python Expression Results Description

len((1, 2)) 2 Length

(1, 2) + (4, 5) (1, 2, 4, 5) Concatenation

(‘CS',) * 2 (‘CS', ‘CS‘) Repetition

5 in (1, 2, 3) False Membership

for x in (4,2,3) :
print 423 Iteration
(x, end = ' ')
BUILT IN FUNCTIONS –TUPLE
Function Description Eg: output
del statement It is used to delete the s=('a','e','i','o','u') ('a', 'e', 'i', 'o', 'u')
tuple. print(s) NameError: name 's' is not
del(s) defined
print(s)
It returns the index of s=(1,2,3,4,5) 3
index( )
first matched item print(s.index(4)) ValueError: tuple.index(x): x
from the tuple. not in tuple
print(s.index(12))

Returns the length of the s=(1,2,3,42.5,5,'red')


len( )
tuple i.e. number of print(len(s)) 6
elements in a tuple
It counts how many s=(12,12,30,42,12)
count( )
times an element has print(s.count(12)) 3
occurred in a tuple and 0
print(s.count(55))
returns it.
It returns True if a tuple s=(12,12,30,42,12)
any ( )
is having at least one print(any(s))
item otherwise False.
tup=() True
print(any(tup)) False
It is used to sort the s=(5,12,30,42,2)
sorted( )
elements of a tuple. It s=sorted(s) [2, 5, 12, 30, 42]
returns a list after #assignment is must [42, 30, 12, 5, 2]
sorting.
print(s)
s=sorted(s, reverse=True)
print(s)
sum( ) It returns sum of the s=(5,12,30,42,2)
elements of the tuple. print(min(s)) 2
Returns the print(max(s)) 42
max( )
element with the print(sum(s)) 91
maximum value
from the tuple.
s=('a','e','i','o','u')
Returns the element with
min( )
the minimum value from print(min(s)) a
the tuple. print(max(s)) u
print(sum(s)) TypeError: unsupported operand
type(s) for +: 'int' and 'str'

PRACTICE SHEET
Q.1 What do you understand by immutability?

Ans: Immutability means not changeable. The immutable types are those that can never change
their value in place. In python following types are immutable –

I. Integers
,strings,Tuple,Booleans,Floating numbers
Q.2 What is the length of the tuple shown below?

T = ((((„a‟, 1), ‟b‟, ‟c‟), ‟d‟, 2), ‟e‟, 3)


Ans: 3, because tuple contains only 3 elements.

Q.3 If a is (1, 2, 3), what is the difference (if any) between a*3 and [a, a, a]?

Ans: a*3 is different from [a,a,a] because, a*3 will produce a tuple (1,2,3,1,2,3,1,2,3) and [a, a, a] will
produce a list of tuples [(1,2,3),(1,2,3),(1,2,3)].

Q.4 If a is (1, 2, 3), is a *3 equivalent to a + a + a?

Ans: Yes

Q.5 If a is (1, 2, 3), what is the meaning of a [1:1] = 9?

Ans: This will produce an error: TypeError: 'tuple' object does not support item assignment

Q.6 How is an empty Tuple created?

Ans: To create an empty tuple we have to write –

>>>T=() or >>>T=tuple()

Q.7 How is a tuple containing just one element created?

Ans: Following methods may be used to create single valued tuple –


>>>T=3, or >>>T=(4,)

Q.8 What is the difference between (30) and (30,)?

Ans: (30) is an integer while (30,) is a tuple.

Short Answer Type Questions

Q.1 How are Tuples different from Lists when both are sequences?

Ans: Tuples are similar to lists in many ways like indexing, slicing, and accessing individual values but
they are different in the sense that –

Tuples are immutable while lists are mutable.

List can grow or shrink while tuples cannot.

Q.2 How can you add an extra element to a tuple?


We can add an extra element to the tuple as
Ans: follows – >>>T = T +(9,) e.g.
Q.3 Find out the output generated by following code fragments:

(a)t1=(1,2,3,4,5) #created tuple

(b) (a, b, c) = (1,2,3) (c) (a, b, c, d) = (1,2,3)

(d) a, b, c, d = (1,2,3) (e) a, b, c, d, e = (p, q, r, s, t) = t1

a. This will assign 1 to a, 2 to b and 3 to c.


b. ValueError: not enough values to unpack (expected 4, got 3)
c. ValueError: not enough values to unpack (expected 4, got 3)
d. If tuple t1 has 5 values then this will assign first value of t1 in to a and p , next value to b and
q and so on.

Q.4 Predict the output –

Ans: True
Q5.x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
O/P
('apple', 'kiwi', 'cherry')

Q6.fruits = ("apple", "banana", "cherry")


(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
O/P
apple
banana
cherry

Q7.# code to test slicing

tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])

(1, 2, 3)
(3, 2, 1, 0)
(2, 3)

Dictionary-
It is an unordered collection of items where each item consist of a key and a value.It is mutable
(can modify its contents ) but Key must be e and immutable.

Characteristics Of a Dictionary
1. Unordered Set
2. Not a sequence
3. Indexed by keys , not Numbers
4. Keys must be Unique
5. Mutable
6. Internally stored as mapping

Creating A Dictionary-It is enclosed in curly braces {} and each item is separated from other
item by a comma(,). Within each item, key and value are separated by a colon (:).

e.g.

d = {‘Subject': 'Computer Science', 'Class': 11}


There are different ways to create dictionary items:
Output

To take input from user


d={}
for i in range(3):
key=int(input("Enter the key"))
value=input("Enter the value")
d[key]=value output
print(d) Enter the key1

Enter the value abc

Accessing dictionary Items Enter the key2

Enter the value xyz


dict = {'Subject': 'Computer Science', 'Class': 11}
print(dict)
OUTPUT
print ("Subject : ", dict['Subject'])
print ("Class : ", dict.get('Class'))

Iterating or Traversing Through A Dictionary

Following example will show how dictionary items can be accessed through loop.

e.g1.
OUTPUT
dict = {'Subject': 'Computer Science', 'Class': 11}
for i in dict: 11

print(dict[i])

Create dictionary with different sequences:


d1={2:99,4:9}
d={(1,2):'ab',3:(4,5),4:[7,8],5:d1, 12.3:{'CS':11}}
print (d)
Output
{(1, 2): 'ab', 3: (4, 5), 4: [7, 8], 5: {2: 99, 4: 9}, 12.3: {'CS': 11}}

To append data in dictionary-To add new set of key-value


Output

Update or Modify Dictionary Elements

We can change the individual element of dictionary.


eg1.

Output

e.g2.

dict = {'Subject': ‘English’, 'Class': 11}


dict['Subject']='computer science'
print(dict)

OUTPUT

{'Class': 11, 'Subject': 'computer science'}


Deleting Dictionary Elements
del, pop() and clear() statement are used to remove elements from the dictionary.

del e.g1.

dict = {'Subject': 'Informatics Practices', 'Class': 11} Output


print('before del', dict)
('before del', {'Class': 11, 'Subject':
del dict['Class'] # delete single element 'Informatics Practices'})
print('after item delete', dict) ('after item delete', {'Subject':
'Informatics Practices'})
del dict #delete whole dictionary
print('after dictionary delete', dict)

eg2:
pop() method is used to remove a particular item in a dictionary. clear() method is used to
remove all elements from the dictionary.
e.g.

dict = {'Subject': 'Computer Science', 'Class': 11} Output


print('before del', dict)
('before del', {'Class': 11,
dict.pop('Class') 'Subject': ‘Computer
Science’})
print('after item delete', dict)

dict.clear()

print('after clear', dict)


BUILT IN FUNCTIONS –DICTIONARY
Dictionary: Python Dictionaries are a collection of some key-value pairs .Dictionaries are
mutable unordered collections with elements in the form of a key:value pairs that associate
keys to values. Dictionaries are enclosed within braces {}

Function Description Eg: output Inva


st
It returns the s={'name':['varun','karan'],'age':[25,20]} S*2
items( )
content of print(s.items()) dict_items([('name', D1+
dictionary as a ['varun','karan']), ('age', [25, d2
list of tuples 20])])
having key-
value pairs.
keys( ) It returns a list of the s={'name':['varun','karan'],'age':[25,20]} dict_keys(['name', 'age'])
key values in a print(s.keys())
dictionary
It returns a list of s={'name':['varun','karan'],'age':[25,20]} dict_values([['varun', 'karan'],
values( )
values from key- print(s.values()) [25, 20]])
value pairs in a
dictionary
It returns the value s={'name':['varun','karan'],'age':[25,20]}
get( )
for the given key ,if print(s.get('age')) [25, 20]
key is not available
print(s.get('class'))
then it returns None
None
copy( ) It creates the copy of s={'name':['varun','karan'],'age':[25,20]} {'name': ['varun', 'karan'], 'age':
the dictionary. x=s.copy() [25, 20]}
s[9]=80 {'name': ['varun', 'karan'], 'age':
[25, 20], 9: 80}
print(x)
print(s)
update() This method merges s={'name':['varun','karan'],'age':
key:value pair from [25,20],'class':11}
the new dictionary d={'Add':'Azaad nagar'} {'name': ['varun', 'karan'], 'age':
into the original
s.update({1:200}) 20, 'class': 11, 1: 200, 'Add':
dictionary.It override
s.update(d) 'Azaad nagar'}
any item if already
exist. s.update({'age':20})
print(s)
Returns the length s={'name':['varun','karan'],'age':[25,20]}
len( )
of the Dictionary print(len(s)) 2
i.e. number of
key:value pairs in
a Dictionary
It is used to create s={'name':['varun','karan'],'age':[25,20]} {'name': ['varun', 'karan'],
fromkeys( )
dictionary from a print(s) 'age': [25, 20]}
collection of {1: 100, 2: 100, 3: 100}
s=dict.fromkeys([1,2,3],100)
keys(tuple/list)
print(s) {1: None, 2: None, 3: None}
v=dict.fromkeys([1,2,3]) {1: [6, 7], 2: [6, 7]}
print(v)
v=dict.fromkeys((1,2),[6,7])
print(v)
This method s={'name':['varun','karan'],'age':
setdefault()
inserts a new [25,20],'class':11} {'name': ['varun', 'karan'],
key:value pair s.setdefault('Marks',(200,300)) 'age': [25, 20], 'class': 11,
only.If key 'Marks': (200, 300), 'Mb':
s.setdefault('Mb',9885244663)
doesn’t already 9885244663}
exists. print(s)
clear( ) It removes all the s={'name':['varun','karan'],'age':[25,20]} {'name': ['varun', 'karan'], 'age':
elements from the print(s) [25, 20]}
Dictionary. {}
s.clear()
print(s)
It sorts the elements v={1:68,3:32,2:50}
sorted( )
of a dictionary by its s={'name':['varun','karan'],'age':[25,20]}
key or values.
v1=sorted(v)
print(v1) [1, 2, 3]
v1=sorted(v.keys()) [1, 2, 3]
print(v1)
[32, 50, 68]
v1=sorted(v.values())
print(v1) [(1, 68), (2, 50), (3, 32)]
v1=sorted(v.items())
['age', 'name']
print(v1)
v1=sorted(s) ERROR
print(v1)
v1=sorted(s.values()) #error
print(v1)
It removes the s={'name':['varun','karan'],'age':[25,20]} {'name': ['varun', 'karan']}
popitem( )
last item from s.popitem()
dictionary and
print(s) TypeError: popitem() takes
also returns the
deleted s.popitem('name') no arguments (1 given)
item.LIFO print(s)
It is used to s={'name':['varun','karan'],'age': {'name': ['varun', 'karan'],
Pop()
delete particular [25,20],'class':11} 'class': 11}
key as mention in s.pop('age') {'name': ['varun', 'karan']}
arguments
print(s)
Returns the v={1:68,3:32,2:50}
max( )
key having s={'name':['varun','karan'],'age':
maximum [25,20],'x':123}
value in the
print(max(s)) x
Dictionary.
print(max(v)) 3
Returns the
min( ) print(min(s))
key having age
minimum print(min(v)) 1
value in the
Dictionary.

PRACTICE SHEET
Q1.Can you modify the keys or value in a dictionary?
Q2. Is dictionary Mutable? Why?
Q3.What is the output produced by the following code –

1. dict1 ={'Eng':15,'Hindi':20}

d1={5:[6,7,8],’a’ : (1,2,3)} t=0

print(d1.keys()) for i in dict1.values():


print(d1.values()) t=t+i

dict_keys([5, 'a']) print(t)

dict_values([[6, 7, 8], (1, 2, 15

3)]) 35

2. setdefault() method returns the value of the


item with the specified key. If the key does not
dict = {'Subject': 'Computer
exist, insert the key, with the specified value.
Science', 'Sec': 'A', 'Class': 11}
x = dict(name = "Aman", country = "India")
dict1 ={'Eng':15,'Hindi':20}
x.setdefault('age',39)
dict2={"Inf.":dict,'Marks':dict1}

print(dict2) x.setdefault(30)

{'Inf.': {'Subject': 'Computer print(x)


Science', 'Sec': 'A', 'Class': 11},
'Marks': {'Eng': 15, 'Hindi': 20}}

d={1:"Neha",2:"Saima"} d={1:["Neha","Avi"],2:"Saima"}

d1=d.copy() #shallow copy d[1].append('Tony')


d1[3]="Kavya" print(d)
print(d) {1: 'Neha', 2: 'Saima'}
print(d.pop(3,-1))

print(d.pop(3,"no value"))
d1=d #deep copy
print(d.pop(2))
d1[3]="Kavya"
{1: ['Neha', 'Avi', 'Tony'], 2: 'Saima'}
print(d)
-1
{1: 'Neha', 2: 'Saima', 3: 'Kavya'} no value

Saima

d={'a':2,'b':3,'c':1} d={'a':2,'bat':3,'ct':1,'fog':4}

e={} s=0
for c in d: for c in d:
e[d[c]]=c
if len(c)>2:
print(e)
s=s+d[c]

print(s)
{2: 'a', 3: 'b', 1: 'c'}
2

d={} WAP to add common keys in third dictionary

d[1]=1 d={1:200,2:300,5:600}
d['1']=2 d1={2:200,1:200}
d[1.0]=4
output
d[1.4]=8
{ {1: 600, 2: 500}
print(d)
d={1:200,2:300,5:100}
{1: 4, '1': 2, 1.4: 8}
d1={2:200,1:400}

d3=d.copy()
d={1:2,2:6,5:10}
d3.update(d1)
s=[2,5]
for i in d:
sum=0
for j in d1:
for i,j in d.items():
if i in s: if i==j:

sum=sum+j d3[i]=d[i]+d1[i]
print(sum) print(d3)
16

Q6. WAP to print a highest value from the given dictionary


dict1 ={'Eng':15,'Hindi':25,'Maths':23}
Ans:
t=0
for i in dict1:
if t<dict1[i]:
t=dict1 [i]
s=i
print("HIGHEST MARKS",t,"in",s)

Q8. WAP to create a dictionary named year whose keys are month names and values are their corresponding number of
days.

Q9.WAP to create a dictionary with the rno., name & marks of n students .Also print the record of those who have
scored>75.
d={}
for i in range(2):
rno=int(input("Enter roll no."))
name=input("Enter name")
marks=int(input("Enter marks"))
d['rno']=rno
d['name']=name
d['marks']=marks
for i in d:
if i=='marks' and 'marks'>'75':
print(d)
Q10.WAP to display whose names are longer than 5 characters.
For example, Consider the following dictionary PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
The output should be: 2 4 LONDON NEW YORK
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
for i in PLACES:
if len(PLACES[i])>5:
print(i,PLACES[i])
Q11.WAP to display key if T2 marks are greater than 20. delete key-value pair whose T2 lesser than 20
Eg. d={1:(20,40),2:(30,10),5:(10,30)}
output: 1 5 {1: (20, 40), 5: (10, 30)}
d={1:(20,40),2:(30,10),5:(10,30)}
for i in d:
if d[i][1]>20:
print(i)
else:
l=i
del d[l]
print(d)

Q12. Which of the following will delete key-value pair for key = “Red” from a dictionary D1?
a. delete D1("Red") b. del D1["Red"] c. del.D1["Red"] d. D1.del["Red"]
Q13. Which of the following statement(s) would give an error during the execution of the following code?
R = {'pno':52,'pname':'Virat', 'expert':['Badminton','Tennis'] ,'score':(77,44)}
print(R) #Statement 1
R['expert'][0]='Cricket ' #Statement 2
R['score'][0]=50 #Statement 3
R['pno']=50 #Statement 4
a. Statement 1 b. Statement 2 c. Statement 3 d. Statement 4
Q14.Given the following dictionaries
dict_student = {"rno" : "53", "name" : 'Rajveer Singh'}
dict_marks = {"Accts" : 87, "English" : 65}
Which statement will append the contents of dict_marks in dict_student?
a. dict_student + dict_marks b. dict_student. Add (dict_marks)
c. dict_student.merge(dict_marks) d. dict_student.update(dict_marks)
Q15.Write the output of the code given below:
my_dict = {"name": "Aman", "age": 26} my_dict['age'] = 27 my_dict['address'] = "Delhi" print(my_dict.items())

Ans: dict_items([('name', 'Aman'), ('age', 27), ('address', 'Delhi')])

Q16.Identify invalid python statement from the following:


a.d=dict() b.e=() c.f=[] d.g=dict{}

Differentiate of built-in functions


Upper() Isupper()
Python upper() method returns Python isupper() method
the uppercased string from the returns “True” if all the
given string. It converts all characters in the string are
lowercase characters to the uppercase; otherwise, It
uppercase. returns “False.”
a = 'we are in the endgame a = 'WE ARE IN THE
now' ENDGAME NOW#'
print(a. upper()) print(a.isupper())
WE ARE IN THE ENDGAME
NOW True

title () capitalize ()
title() function in Python is the In Python,
Python String Method which is the capitalize() method
used to convert the first converts the first character of
character in each word to a string
Uppercase and remaining to a capital (uppercase) letter.
characters to Lowercase If the string has its first
in the string and returns a new character as capital, then it
string. returns the original string.
str1 = 'learning pYTHon iS str1 = 'learning pYTHon iS
easy' easy'
str2 = str1.title() str2 = str1.capitalize()
print ( str2) print ( str2)
Learning Python Is Easy
Learning python is easy

isalpha() isalnum()
The Python isalpha() method isalnum() only returns true if a
returns true if a string only string contains alphanumeric
contains letters. characters(alphabets or
numbers), without symbols.
str1='abcd' str1='abcd'
print(str1.isalpha()) print(str1.isalnum())
str1 = 'learning pYTHon iS str1 = 'learning pYTHon iS
easy' easy'
print(str1.isalpha() ) print(str1.isalnum() )
str1='12abcd' str1='12abcd'
print ( str1.isalpha()) print ( str1.isalnum())
str1=' ' str1='12abcd#'
print(str1.isalpha()) print ( str1.isalnum())
str1='12abcd#' str1=' '
print ( str1.isalpha()) print(str1.isalnum()))
True True
False False
False True
False False
False False

Strip() split()
It returns the string after removing the space from the
both sides of the string. It Returns a copy of the string
split() method in Python split a
string into a list of strings
after breaking the given string
by the specified separator.
string = " python is easy " text = 'Python is easy'
print(string.strip()) print(text .split())
print(string.strip(' saey ')) word = 'Python: is: easy'
print(word .split(':'))
word = 'CatBatSatFatOr'
print(word .split('t'))
python is easy ['Python', 'is', 'easy']
python i ['Python', ' is', ' easy']
['Ca', 'Ba', 'Sa', 'Fa', 'Or']

pop() and remove()


del
del is a keyword and pop() is a remove() method delete values
built in method both deletes or object from the list using
values or object from the list value. The remove() method
using an index. pop() returns removes the first matching
deleted value. value from the list.

numbers = [1, 2, 3, 2, 3, 4, 5] numbers = [1, 2, 3, 2, 3, 4, 5]


del numbers[2] numbers. remove(2)
print(numbers) print(numbers)
numbers.pop() print(numbers. remove(1))
print(numbers) print(numbers)
print(numbers.pop(-1))
print(numbers)
[1, 2, 2, 3, 4, 5] [1, 3, 2, 3, 4, 5]
[1, 2, 2, 3, 4] None # not return
4 any value
[1, 2, 2, 3] [3, 2, 3, 4, 5]
clear(): clear() method in python is used to empty the entire list.
this can be used if someone wants an empty list for any other
purpose.
Eg:
numbers = [1, 2, 3, 2, 3, 4, 5]
print(numbers)
numbers.clear()
print(numbers)

o/p
[1, 2, 3, 2, 3, 4, 5]
[]
.

Find() index()
It is used to search the first It also searches the first
occurance of the substring in occurance and returns the
the given string. It returns -1 if lowest index of the substring
substring not in string if a substring is not found in a
find() can be used only string ,it raises ValueError
with strings exception.
index() can be applied to lists,
tuples along with strings.
numbers = 'abcdefgh' numbers = 'abcdefgh'
print(numbers. find('cd',3,5)) print(numbers. index('cd',0,4))
print(numbers. find('cd')) print(numbers. index('cd'))
print(numbers .find('cd',2)) print(numbers. index('cd',5,6))

2
-1 2
2 Traceback (most recent call
2 last):
File "<string>", line 7, in
<module>
ValueError: substring not
found
The count() method will return an integer value, i.e., the count
of the given element from the given string. It returns a 0 if the
value is not found in the given string.
Eg:
numbers = 'abcdefghcdCD'
print(numbers. count('cd'))
print(numbers. count('cd',3,5))

O/P
2
0
Update()
Copy()
method updates the
update() This method returns a shallow
dictionary with the elements from copy(only keys are copied) of
the another dictionary object or the dictionary. It doesn't
from an iterable of key/value modify the original dictionary.
pairs.
Dictionary1 = { 'A': 'Python', 'B': d1 = {1:'one', 2:'two'}
'For', } d2 = d1.copy()
Dictionary2 = { 'B': 'Study', 'C': print('Orignal: ',d1)
'Learn' } print('New: ',d2)
print(Dictionary1) d3=d2
Dictionary1.update(Dictionary2) print(d3)
print(Dictionary1) d3.clear()
print(Dictionary1.update(D='Start')) print(d3,d2,d1)
print(Dictionary1)
{'A': 'Python', 'B': 'For'} Orignal: {1: 'one', 2: 'two'}
{'A': 'Python', 'B': 'Study', 'C': New: {1: 'one', 2: 'two'}
'Learn'} {1: 'one', 2: 'two'}
None {} {} {1: 'one', 2: 'two'}
{'A': 'Python', 'B': 'Study', 'C':
'Learn', 'D': 'Start'}

Append() Extend()
It adds a single item to the end It adds one list at the ends of
of the list another list.
my_list = ['python', 'for'] my_list = ['python', 'is']
my_list.append('learning') my_list.extend('easy')
print (my_list) print (my_list)
my_list.append([1,2]) my_list.extend([1,2])
print(my_list) print(my_list)
['python', 'for', 'learning'] ['python', 'is', 'e', 'a', 's', 'y']
['python', 'for', 'learning', [1, 2]] ['python', 'is', 'e', 'a', 's', 'y', 1,
2]

Sort()
Sorted()
function is very similar to
sort() sorted() method sorts the given

sorted() but unlike sorted it sequence either in ascending


returns nothing and makes order or in descending order
changes to the original and always return the a sorted
sequence. Moreover, sort() is list. This method does not
a method of list class and can effect the original sequence.
only be used with lists. sequence list, tuple, string or
dictionary.
numbers = [1, 3, 4, 2] numbers =[1, 3, 4, 2]
numbers. sort() numbers1=sorted(numbers)
print(numbers) print(numbers1)
numbers. sort(reverse=True) numbers={4:'a',1:'b',3:'c'}
print(numbers) numbers1=sorted(numbers,
reverse=True)
print(numbers1)
numbers="1265"
numbers1=sorted(numbers,
reverse=True)
print(numbers1)
[1, 2, 3, 4] [1, 2, 3, 4]
[4, 3, 2, 1] [4, 3, 1]
['6', '5', '2', '1']

Setdefault()
fromkeys()
It is used to create a new dictionary from a sequence
It inserts a new key: value pair containing all the keys and a common value,which will be
If not available, it inserts key assigned to the keys.

with a value to the dictionary.


Dictionary1 = { 'A': 'PYTHON', d={}
'B': 'C++', 'C':'JAVA'} d=dict. fromkeys([2,3,4],100)
Dictionary1.setdefault(5,300) print(d)
print(Dictionary1) d=dict. fromkeys((2,3,4))
Dictionary1.setdefault('C',300) print(d)
print(Dictionary1) d=dict. fromkeys([2,3,4],
Dictionary1.setdefault(6) (100,200))
print(Dictionary1) print(d))
{'A': 'PYTHON', 'B': 'C++', 'C': {2: 100, 3: 100, 4: 100}
'JAVA', 5: 300} {2: None, 3: None, 4: None}
{'A': 'PYTHON', 'B': 'C++', 'C': {2: (100, 200), 3: (100, 200), 4:
'JAVA', 5: 300} (100, 200)}
{'A': 'PYTHON', 'B': 'C++', 'C':
'JAVA', 5: 300, 6: None}

31. Which of the following is not a python legal string operation.


i. ‘abc’+’aba’ ii. ‘abc’*3 iii. ‘abc’+3 iv.
‘abc’.lower()

32. Which of the following is not a valid string operation.


i. Slicing ii. concatenationiii. Repetition iv.
Floor

33. Which of the following is a mutable type.


i. string ii. tuple iii. int iv. List
34. What will be the output of the following code
str1=”I love Python” strlen=len(str1)+5 print(strlen)
i.18 ii.19 iii.13 iv.15

35. Which method removes all the leading whitespaces from the left of the string.
i. split() ii.remove() iii. lstrip() iv rstrip()

36. It returns True if the string contains only whitespace characters, otherwise
returns
False.
i) isspace() ii.strip() iii.islower() iv. isupper()

37. It converts uppercase letter to lowercase and vice versa of the given string.
i. lstrip() ii.swapcase() iii.istitle() iv. count()

38. What will be the output of the following code.


Str=’Hello World! Hello Hello’ Str.count(‘Hello’,12,25)
i.2 ii.3 iii.4 iv. 5

39. What will be the output of the following code.


Str=”123456”
print(Str.isdigit())
i.True ii. False iii.None iv.Error

40. What will be the output of the following code.


Str=”python 38” print(Str.isalnum())
iii. True ii.False iii.None iv. Error
41. What will be the output of the following code.
Str=”pyThOn” print(Str.swapcase())
i.PYtHoN ii. pyThon iii.python iv.PYTHON

42. What will be the output of the following code.


Str=”Computers” print(Str.rstrip(“rs”))
i. Computer ii.Computers iii.Compute iv. Compute

43. What will be the output of the following code.


Str=”This is Meera\’ pen” print(Str.isdigit())
i.21 ii.20 iii.18 iv.19

String Slicing
s='welcome'
w E L C O M e

Answers
1.print(s[2:6])
2.print(s[1:6:2])
3.print(s[1:5:2]) 1. lcom
4.print(s[:4])
5.print(s[2:]) 2. ecm
6.print(s[1::2]) 3. ec
7.print(s[6:])
8.print(s[10:]) 4. welc
9.print(s[:-6])
5. lcome
10.print(s[-6:-1:-2])
11.print(s[-6:-1:2]) 6. ecm
12.print(s[-4:-1:1])
13.print(s[:-4:-1]) 7. e
8.’ ’
14.print(s[-4:-1:2])
15.print(s[::2])
16.print(s[:10])
17.print(s[10:15])
18.print(s[::-1])
19.print(s[:4]+s[4:])

Nested List Slicing


l=[1,2,[3,4,[5,6]],7,8]
1. print(l[1:]) Answers

2. print(l[2][2][1]) 1. [2, [3, 4, [5, 6]], 7, 8]


3. print(l[2][2][:1])
4. print(l[2][2][1:]) 2. 6
5. print(l[2][:2])
3. [5]
6. print(l[2][2])
7. print(l[2][2][0]) 4. [6]
8. print(l[2][1:])
9. print(l[2][:1]) 5. [3, 4]
10. print(l[2][2][0:]) 6. [5, 6]

44. How many times is the word ‘Python’ printed in the following statement.
s = ”I love Python”
for ch in s[3:8]:
print(‘Python’)
i. 11 times ii. 8 times iii. 3 times iv. 5 times
45. Which of the following is the correct syntax of string slicing:
str_name[start:end] iii. str_name[start:step]
str_name[step:end] iv. str_name[step:start]

46. What will be the output of the following code? A=”Virtual Reality”
print(A.replace(‘Virtual’,’Augmented’))
Virtual Augmented iii. Reality Augmented
Augmented Virtual iv. Augmented Reality

47. What will be the output of the following code?


print(“ComputerScience”.split(“er”,2))
[“Computer”,”Science”] iii. [“Comput”,”Science”]
[“Comput”,”erScience”] iv. [“Comput”,”er”,”Science”]

48. Following set of commands are executed in shell, what will be the
output?
>>>str="hello"
>>>str[:2]
i. he ii. lo iii. olleh iv. hello

49. ………..function will always return tuple of 3 elements.


i. index() ii. split() iii. partition() iv. strip()

50. What is the correct python code to display the last four characters of
“Digital India”
i. str[-4:] ii. str[4:] iii. str[*str] iv. str[/4:]
51. Given the list L=[11,22,33,44,55], write the output of print(L[: :-1]).
i. [1,2,3,4,5] ii. [22,33,44,55] iii. [55,44,33,22,11] iv.
Error in code

52. Which of the following can add an element at any index in the list?
i. insert( ) ii. append( ) iii. extend() iv. all of these

53 Which of the following function will return a list containing all the words o
the given string?
i . split() ii. index() i i i . count() iv. list()

54. Which of the following statements are True. a. [1,2,3,4]>[4,5,6]


b. [1,2,3,4]<[1,5,2,3]
c. [1,2,3,4]>[1,2,0,3]
d. [1,2,3,4]<[1,2,3,2]
i.a,b,d ii. a,c,d iii. a,b,c iv. Only d

55. If l1=[20,30] l2=[20,30] l3=[‘20’,’30’] l4=[20.0,30.0] then which of the


following statements will not return ‘False’:
a. >>>l1==l2 b. >>>l4>l1 c. >>>l1>l2 d. >>> l2==l2
i. b, c ii. a,b,c iii. a,c,d iv. a,d

56. >>>l1=[10,20,30,40,50]
>>>l2=l1[1:4]
What will be the elements of list l2:
i. [10,30,50] ii. [20,30,40,50] iii. [10,20,30] iv. [20,30,4

57. >>>l=[‘red’,’blue’]
>>>l = l + ‘yellow’
What will be the elements of list l:
i. [‘red’,’blue’,’yellow’] ii. [‘red’,’yellow’] iii. [‘red’,’blue’,’yellow’]
iv. Error

58. What will be the output of the following code:


>>>l=[1,2,3,4]
>>>m=[5,6,7,8]
>>>n=m+l
>>>print(n)
[1,2,3,5,6,7,8] ii. [1,2,3,4,5,6,7,8] iii. [1,2,3,4][5,6,7,8]
iv. Error

59. What will be the output of the following


code:
>>>l=[1,2,3,4]
>>>m=l*2
>>>n=m*2
>>>print(n)
i [1,2,3,4,1,2,3,4,1,2,3,4] ii.
[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]
iii. [1,2,3,4] [4,5,6,7] iv. [1,2,3,4]

60. Match the columns: if

>>>l=list(‘computer’)

Column A Column B
1. L[1:4] a. [‘t’,’e’,’r’]
2. L[3:] b. [‘o’,’m’,’p’]
3. L[-3:] c. [‘c’,’o’,’m’,’p’,’u’,’t’]
4. L[:-2] d. [‘p’,’u’,’t’,’e’,’r’]

I 1-b,2-d,3-a,4-c iii. 1-c,2-b,3-a,4-d


ii 1-b,2-d,3-c,4-a iv. 1-d,2-a,3-c,4-b

61. If a list is created as


>>>l=[1,2,3,’a’,[‘apple’,’green’],5,6,7,[‘red’,’orange’]]

then what will be the output of the following statements:


>>>l[4][1]
i. ‘apple’ iii. ‘green’
ii. ‘red’ iv. ‘orange’
62. >>>l[8][0][2]
i.‘d’ iii. ‘e’
ii.‘r’ iv. ‘o’
63. >>>l[-1]
i.[‘apple’,’green’] iii. [‘red’,’orange’]
ii.[‘red’ ] iv. [’orange’]
64 >>>len(l)
i. 10 iii. 9
ii. 8 iv 11
65. What will be the output of the following code:
>>>l1=[1,2,3]
>>>l1.append([5,6])
>>>l1
i.[1,2,3,5,6] ii. [1,2,3,[5,6]] iii. [[5,6]]
iv. [1,2,3,[5,6]]
66. What will be the output of the following code:
>>>l1=[1,2,3]
>>>l2=[5,6]
>>>l1.extend(l2)
>>>l1
i.[5,6,1,2,3] ii. [1,2,3,5,6] iii. [1,3,5]
iv. [1,2,3,6]
67. What will be the output of the following code:
>>>l1=[1,2,3]
>>>l1.insert(2,25)
>>>l1
iii. [1,2,3,25] ii. [1,25,2,3] iii. [1,2,25,3]
iv. [25,1,2,3,6]
68. >>>l1=[10,20,30,40,50,60,10,20,10]
>>>l1.count(‘10’)
i. 3 ii. 0 iii.2 iv. 9
69. Which operators can be used with list?
i. in ii. not in iii. both (i)&(ii) iv. Arithmetic
operator only
70. Which of the following function will return the first
occurrence of the specified element in a list.
i. sort() ii. value() iii. index() iv. sorted()
71. Which of the statement(s) is/are correct.
Python dictionary is an ordered collection of items.
Python dictionary is a mapping of unique keys to values
Dictionary is mutable.
All of these.
72. ………function is used to convert a sequence data type
into tuple.
i. List() ii tuple() iii TUPLE iv. tup()
73. It tup=(20,30,40,50), which of the following is incorrect
i. print(tup[3]) ii. tup[2]=55 iii.
print(max(tup)) iv. print(len(tup))
74. Consider two tuples given below:
>>>tup1=(1,2,4,3)
>>>tup2=(1,2,3,4)

What will the following statement print(tup1<tup2)


i.True ii. False iii.Error iv. None of
these
75. Which function returns the number of elements in the
tuple
i. len( ) ii. max( ) iii. min( ) iv.
count( )
76. Which function is used to return a value for the given key.
i. len( ) ii. get( ) iii. keys( ) iv. None of these
77. Keys of the dictionary must be
i.similar ii. unique iii. can be similar or unique iv. All of
these
78. Which of the following is correct to insert a single element in a tuple .
i.T=4 ii. T=(4) iii. T(4,) iv. T=[4,]
79. Which of the following will delete key-value pair for key=’red’ form a
dictionary D1
i.Delete D1(“red”) ii. del. D1(“red”) iii. del D1[“red”]
iv. del D1
80. Which function is used to remove all items form a particular
dictionary.
i.clear( ) ii. pop( )iii. delete iv. rem( )
81. In dictionary the elements are accessed through
i.key ii. value iii. index iv. None of these
82. Which function will return key-value pairs of the dictionary
i.key( ) ii. values( ) iii. items( ) iv. get( )
83 Elements in a tuple can be of type.
i.Dissimilar ii. Similar iii. both i & ii iv.
None of these
84 To create a dictionary , key-value pairs are separated by…………….
i.(;) ii. ( , ) iii. (:) iv. ( / )
85 Which of the following statements are not correct:
An element in a dictionary is a combination of key-value pair
A tuple is a mutable data type
We can repeat a key in dictionary
clear( ) function is used to deleted the dictionary.

i.a,b,c ii.b,c,d iii. b,c,a iv. a,b,c,d


86 Which of the following statements are correct:
Lists can be used as keys in a dictionary
A tuple cannot store list as an element
We can use extend() function with tuple.
We cannot delete a dictionary once created.

i.a,b,c ii.b,c,d iii.b,c,a iv. None of these


87 Like lists, dictionaries are which mean they can be changed.

i.Mutable ii. immutable iii.variable iv. None of these


88 To create an empty dictionary , we use

i.d=[ ] ii. d =( ) iii. d = {} iv. d= < >


89 To create dictionary with no items , we use

ii. Dict ii. dict( ) iii. d = [ ] iv. None of these


90 What will be the output
>>>d1={‘rohit’:56,”Raina”:99}
>>>print(“Raina” in d1)

i. True ii.False iii.No output iv. Error


91 Rahul has created the a tuple containing some numbers as
>>>t=(10,20,30,40)
now he wants to do the following things help him

1. He want to add a new element 60 in the tuple, which statement he


should use out of the given four.
i. >>>t+(60)
ii. >>>t + 60
iii. >>>t + (60,)
iv. >>>t + (‘60’)
92 Rahul wants to delete all the elements from the tuple, which
statement he should use
>>>del t
>>>t.clear()
>>>t.remove()
>>>None of these
93 Rahul wants to display the last element of the tuple, which statement
he should use
>>> t.display()
>>>t.pop()
>>>t[-1]
>>>t.last()
94 Rahul wants to add a new tuple t1 to the tuple t, which statement he
should use i.
>>>t+t1
>>>t.add(t1)
>>>t*t1
None of these
95 Rahul has issued a statement after that the tuple t is replace with
empty tuple, identify the statement
he had issued out of the following:
>>> del t
>>>t= tuple()
>>>t=Tuple()
>>>delete t
96 Rahul wants to count that how many times the number 10 has come:
>>>t.count(10)
>>>t[10]
>>>count.t(10)
None of these
97 Rahul want to know that how many elements are there in the tuple t,
which statement he should use
out of the given four
>>>t.count()
>>>len(t)
>>>count(t)
>>>t.sum()
98 >>>t=(1,2,3,4)
Write the statement should be used to print the first three elements 3
times
>>>print(t*3)
>>>t*3
>>>t[:3]*3
>>>t+t
99 Match the output with the statement given in
column A with Column B
1. >>>tuple([10,20,30]) a. >>> (10,20,30)
2. >>>(“Tea”,)* 3 b. >>> 2
3. >>>tuple(“Item”) c. >>> ('Tea', 'Tea', 'Tea') 4.
4. >>>print(len (tuple([1,2]))) d. >>> ('I', 't', 'e', 'm')

i. 1-b,2-c,3-d,4-a
ii. 1-a,2-c,3-d,4-b
iii. 1-c,2-d,3-a,4-a
iv. 1-d,2-a,3-b,4-c
100 Write the output of the following code:
>>>d={‘name’:’rohan’,’dob’:’2002-03-
11’,’Marks’:’98’}
>>>d1={‘name’: ‘raj’)
>>>d1=d.copy()
>>>print(“d1 :”d1)
i. d1 : {'name': 'rohan', 'dob': '2002-03-
11', 'Marks': '98'}
ii. d1 = {'name': 'rohan', 'dob': '2002-
03-11', 'Marks': '98'}
iii. {'name': 'rohan', 'dob': '2002-03-11',
'Marks': '98'}
iv. (d1 : {'name': 'rohan', 'dob': '2002-
03-11', 'Marks': '98'})
ANSWERS

1 ii 2 i 3 iii 4 iii 5 iv 6 ii 7 iii


8 i 9 i 10 i 11 ii 12 iii 13 ii 14 i
15 iii 16 i 17 i 18 iii 19 i 20 i 21 ii
22 iii 23 iii 24 iv 25 iv 26 i 27 iii 28 i
29 i 30 iv 31 iii 32 iv 33 iv 34 i 35 iii
36 i 37 ii 38 i 39 i 40 ii 41 i 42 iii
43 iv 44 iv 45 i 46 iv 47 iii 48 i 49 iii
50 i 51 iii 52 i 53 i 54 iii 55 iv 56 iv
57 iv 58 ii 59 ii 60 i 61 iii 62 i 63 iii
64 iii 65 iv 66 ii 67 iii 68 ii 69 iii 70 iii
71 iv 72 ii 73 ii 74 ii 75 i 76 ii 77 ii
78 iii 79 iii 80 i 81 i 82 iii 83 iii 84 iii
85 ii 86 iv 87 i 88 iii 89 ii 90 i 91 iii
92 i 93 iii 94 i 95 ii 96 i 97 ii 98 iii
99 ii 100 i

You might also like