Question Bank - All Sequences
Question Bank - All Sequences
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.
Mybook (ii) Break (iii) _DK (iv) My_book (v) PaidIntrest (vi) s-num (vii)percent (viii) 123
(ix) dit km (x) class
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.
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”)
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:
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)
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[1:6:2] “mzn”
Word[-7:-3:3] “az”
Word[::-2] “giaa”
Creating String
e.g.
a=‘Computer Science'
b=“Informatics Practices“
print('str-',str)
#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.
OUTPUT
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
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
Q4. What would following expression return? To remove all the white spaces from the beginning of a
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)
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.
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=[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
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)
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.
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)
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
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]
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))
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?
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)].
Ans: Yes
Ans: This will produce an error: TypeError: 'tuple' object does not support item assignment
>>>T=() or >>>T=tuple()
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 –
Ans: True
Q5.x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
O/P
('apple', 'kiwi', 'cherry')
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.
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])
Output
e.g2.
OUTPUT
del e.g1.
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.clear()
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}
3)]) 35
print(dict2) x.setdefault(30)
d={1:"Neha",2:"Saima"} d={1:["Neha","Avi"],2:"Saima"}
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[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
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())
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']
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
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.
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()
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:])
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
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
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()
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
>>>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-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