Python Short Question Answers
Python Short Question Answers
Bhaskar V
Premkumar P
Unit I
Short Questions
2
9. What is meant by computational complexity of an algorithm?
It is the execution time of the algorithm in terms of its input parameters.
10. Give the advantages and limitations of flowchart.
Advantages: it makes the logic clear and visual. It communicates
the interconnection of the logical system. The problem can be well
analysed. Useful for coding the problem. Testing and debugging is
easily done. Flowcharts are good programming documentation for
future reference. Disadvantages: it is complicated. It is costly and
difficult to modify in future and no updates are easy to do.
11. Give the advantages and limitations of pseudocode.
Advantages: it is language independent. It is easier to develop
program from pseudocode than from flowchart. It is very compact
than a flowchart. Limitations: Pseudocode may vary for different
programming languages thus it is implementation specific so not
every developer can understand.
12. Name the three basic program control structures.
Sequence, selection and repetition.
13. Write the algorithm for finding the sum of any two numbers
Let the two numbers be A and B and let their sum be equal to C.
Then, the desired algorithm is given as follows:
1. START
2. PRINT “ENTER ANY TWO NUMBERS”
3. INPUT A,B
4. C ← A + B
5. print C
6. STOP
14. Write an algorithm to check whether the given number is
odd or even.
Let the number to be checked be represented by N. The number
N is divided by 2 to give an integer quotient, denoted by Q. If
3
the remainder, designated as R, is zero, N is even; otherwise N
is odd. This logic has been applied in the following algorithm:
1. START
2. print “ENTER THE NUMBER”
3. INPUT N
4. Q ← N/2 (INTEGER DIVISION)
5. R←N −Q×2
6. if R = 0 then
7. print “N IS EVEN”
8. if R = 1 then
9. print “N IS ODD”
10. STOP
15. Write an algorithm to print the largest of 3 numbers.
Let the three numbers be represented by A, B, and C. There can be
three ways of solving the problem. The three algorithms, with some
differences, are given below:
1. START
2. print “Enter Three Numbers”
3. INPUT A, B, C
4. if A > B then
5. if A > C then
6. print A
7. else
8. if C > B then
9. print C
10. else
11. print B
12. else
13. if B > C then
14. print B
15. else
4
16. print C
17. STOP
The following algorithm uses ’AND’ operator to simplify the logic of
execution:
1. START
2. print "ENTER THE THREE NUMBERS A, B, C"
3. READ A, B, C
4. if A > B and A > C then
5. print A
6. if B > C and C > A then
7. print B
8. else
9. print C
10. STOP
The following algorithm uses a variable MAX to store the largest
number.
1. START
2. print “ENTER THREE NUMBERS”
3. INPUT A, B, C
4. M AX ← A
5. if B > M AX then
6. M AX ← B
7. if C > M AX then
8. M AX ← C
9. print M AX
10. STOP
16. List few of the flow-chart symbols:
See Figure 1
17. Mention the guidelines for drawing flow-charts.
• In drawing a proper flowchart, all necessary requirements should
be listed out in a logical order.
5
Start
Input Process
Decision Output
Stop
Process1 Process2
No Decision1 Yes
6
• Communication Flowcharts are a better way of communicating
the logic of a system to all concerned.
• Effective analysis With the help of flowcharts, problems can be
analysed more effectively.
• Proper documentation Program flowcharts serve as a good program
documentation needed for various purposes.
• Efficient coding Flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
• Proper debugging Flowcharts help in the debugging process.
• Efficient program maintenance The maintenance of an operating
program become easy with the help of a flowchart.
Limitations of using flowcharts
• Complex logic Sometimes, the program logic is quite complicated.
In such a case, a flowchart becomes complex and clumsy.
• Alterations and modifications If alterations are required, the flowchart
may need to be redrawn completely.
• Reproduction Since the flowchart symbols cannot be typed in, the
reproduction of a flowchart becomes a problem.
• The essentials of what has to be done can easily be lost in the
technical details of how it is to be done.
19. Draw a flowchart to find the sum of the first 50 natural
numbers
See Figure: 3
20. Draw a flowchart to find the largest of three numbers A, B,
and C.
See Figure: 4
21. Give comment on pseudocode and actual/real code
What separates pseudocode from “real” code is that in pseudocode,
we employ whatever expressive method is most clear and concise
to specify a given algorithm. Sometimes, the clearest method is
7
Start N ←N +1
SUM=0 SU M ← SU M + 1
N=0
IS N > 50?
No
Yes
PRINT SU M
STOP
Unit I
Big Questions
8
Start
READ A, B, C
Yes
Is B > C? Is A > B? Is A > C?
Yes No YES
No No
STOP
11
new value of a ← old value of b;
new value of b ← old value of a
What we have done with our present proposal is to make the assignment
new value of b ← new value of a.
In other words when we execute step (2) we are not using the value a,
that will make things work correctly—because a has already changed.
To solve this exchange problem, we need to find a way of not destroying
"the old value of a" when we make the assignment a ← b
A way to do this is to introduce a temporary variable t and copy the
original value of a into this variable before executing step (1). The
steps to do this are:
t ← a; (3)
a ← b; (4)
After these two steps we have
a : 456 t : 123 b : 456
Now we have to copy down the value of t to b so that we will be able
to achieve exchanging the values between a and b.
b ← t; (5)
ACTION 2
ACTION n
Statement
Once the sequence of steps in the selected path has been carried out,
the paths are rejoined and then the next instruction is carried out.
Thus, the selection structure has only a single entry and a single exit.
In the example given in Figure 6a, we have a Test expression which
is evaluated. In the selection process, if the expression is true then
the statement is executed if the expression is false, the statement
is bypassed Figure 6a. In Figure 6b, if the Test expression evaluates
to True, then, statement1 is executed otherwise statement2 will
be executed
13
False
Condition
Repeated Task
True
False
Condition Repeated Task
True
(a) repeat. . . until – post-test loop (b) while – pre-test loop
COU N T ← 0
COU N T ← COU N T + 1
Print COU N T
No
Stop
16
1. for j = 2 to A.length do
2. key = A[j]
3. //Insert A[j] into the sorted sequence A[1..j − 1].
4. i=j−1
5. while i > 0 and A[i] > key do
6. A[i + 1] = A[i]
7. i=i−1
8. A[i + 1] = key
Algorithm 1: Insertion-Sort
we are checking first whether the key is smaller than the card at the
ith position. If so, then shift it to the right and we terminate the
inner loop as soon as we come across a card, that is smaller than key
and thereby insert the card one position above the smaller card also
if the smallest card on hand happens to be larger than the key and
will obviously be inserted into the lowest position.
At the start of each iteration of the for loop of lines 1–8, the subarray
A[1..j − 1] consists of the elements originally in A[1..j − 1], but in
sorted order.
We use loop invariants to help us understand why an algorithm is
correct. We must show three things about a loop invariant.
Initialization: It is true prior to the first iteration of the loop.
Maintenance: If it is true before an iteration of the loop, it remains
true before the next iteration.
Termination: When the loop terminates, the invariant gives us a
useful property that helps show that the algorithm is correct.
When the first two properties hold, the loop invariant is true prior to
every iteration of the loop. (Of course, we are free to use established
facts other than the loop invariant itself to prove that the loop
invariant remains true before each iteration.) Note the similarity
to mathematical induction, where to prove that a property holds,
we prove a base case and an inductive step. Here, showing that
the invariant holds before the first iteration corresponds to the base
17
case, and showing that the invariant holds from iteration to iteration
corresponds to the inductive step. The third property is perhaps
the most important one, since we are using the loop invariant to
show correctness. Typically, we use the loop invariant along with
the condition that caused the loop to terminate. The termination
property differs from how we usually use mathematical induction,
in which we apply the inductive step infinitely; here, we stop the
“induction” when the loop terminates.
6. Develop an algorithm and flowchart to find the minimum
and maximum in a list of numbers.
In this algorithm let us use the function length(list) see Algorithm
2 which will return the length of the argument list. Let us also use
two variables called min and max which will hold the minimum and
maximum of the list under consideration. The while loop can be
used to traverse over the list in checking the values of the variables
in and update the min and max variables as and when we come across
a smaller and larger values. The index variable i which is initialised
as 0 before the entry into the while loop will be incremented by 1
each step as the loop advances in the list. The flowchart is hown in
Figure 11
7. Write an algorithm to insert a card into a list of sorted
cards.
Let us assume that we hold the sorted cards in the left hand and the
card to e inserted is on the table. This can be shown as below:
x
Sorted cards j th
When we want to insert the card x into the sorted cards, then we
must know which position among the sorted cards, it can be inserted.
Let the number of sorted cards be j then if we assume the first array
position as 0 and then the position of the last card in the sorted cardsl
be j − 1; If the card in hand happens to be smaller than the card at
the (j − 1)th position, we would need to shift it to the j th position
18
1. READ a list of numbers
2. min ← list[0]
3. max ← list[0]
4. i←0
5. length ← lengthof list
6. while i < length do
7. if min > list[i] then
8. min ← list[i]
9. if max < list[i] then
10. max ← list[i]
11. i←i+1
12. print min, max
Algorithm 2: Find maximum and minimum of a list of numbers
READ the Is
No
list of numbers i < length?
Yes
min ← list[0]
max ← list[0]
Is
Yes min > list[i]
length ← length
of list
min ← list[i]
No
i←0
Yes Is
max < list[i]
max ← list[i]
No
STOP
n! = n × (n − 1) × (n − 2) × . . . × 3 × 2 × 1.
Since, 0! = 1, when initially, n = 0, the condition i = n becomes
20
immediately True and our program doesn’t enter the loop at all. If
n > 0, the looping will take place at least once. In every iteration, i
is incremented by 1 and it gets multiplied with f act and the result is
assigned to f act itself. Thus the loop will terminate when i = n and
at that time, the f act value will be the factorial of n. The algorithm
3 and flow-chart for computing factorial is shown in Figure: 12
1. READ n // n ≤ 0
2. i←0
3. f act ← 1
4. while i < n do
5. i←i+1
6. f act ← i × f act
7. print f act
Algorithm 3: Factorial Algorithm(Iterative)
21
Start
READn
i←0
f act ← 1
Is i = n? Yes
No
i←i+1
Print f act
f act ← f act × i
Stop
22
• A third pillar B to store one or more disks while they were being
moved from their original source A to their destination C
Consider the following recursive solution to this problem:
1. If N = 1, merely move the disk from A to C.
2. If N = 2, move 1st disk from A to B. Then move 2nd disk from
A to C. Then move 1st disk from B to C.
3. If N = 3, call upon the technique already established in (2) to
move the first 2 disks from A to B using C as an intermediate.
Then move the 3rd disk from A to C. Then use the technique in
(2) to move 2 disks from B to C using A as an intermediate.
4. For general N , use the technique already established to move
N − 1 disks from A to B using C as an intermediate. Then move
one disk from A to C. Then again use the technique already
established to move N − 1 disks from B to C using A as an
intermediate.
N − 1 disks
...
...
N disks
A B C A B C
(a) Initial State (b) Second State if N > 3
Notice that the technique described here calls upon itself, but switches
the order of parameters in so doing. This can be formalized in the
following pseudo code:
FUNCTION HANOI(N, SOURCE, DESTINATION, INTERMEDIATE)
VAR L1,L2:LABEL
VAR N: INTEGER
VAR SOURCE, DESTINATION, INTERMEDIATE: CHARACTER
23
N − 1 disks
...
N disks
A B C A B C
(a) Third State (b) Goal State
IF N = 1 THEN
WRITE "MOVE DISK FROM" SOURCE, "TO" DESTINATION
RETURN
ENDIF
CALL HANOI (N-1, SOURCE, INTERMEDIATE, DESTINATION)
(*In all recursive call HANOI works with value N less 1*)
L1: WRITE "MOVE DISK FROM" SOURCE, "TO", DESTINATION
CALL HANOI(N-1, INTERMEDIATE, DESTINATION, SOURCE)
L2: RETURN
END HANOI
Because we have a CALL to HANOI within the function HANOI,
this represents a recursive CALL. Although such a function is easy
to write in pseudo-code, it is somewhat more difficult to understand
thoroughly
The key to understanding the function is to be aware of what a
compiler must do when the recursive call is made.The difficulty with
handling recursion is that, because we call a function from within
the function, eventually a return will be made to that same function.
However, because the call also involves changing the values of the
function’s parameters the old values of the parameters will have been
destroyed upon return unless they preserved before the recursive call.
The best way of preserving them is to stack them with the return
address. Thus, a recursive call involves stacking not only a return
address but also values of all parameters essential to the current
24
state of the function. In this sense, it is crucial that all functions
which are recursively called receive actual working copies of their
parameters rather than merely the memory addresses of the calling
program’s variables. That is, recursively called functions should
receive parameters by value, not by reference. To illustrate, we will
trace through the actions taken when a call of the form
CALL HANOI(3,"A","C","B")
is initiated. Figure 13a and 14b (here "A" is the source, "C" is the
destination and N = 3)
1. N is not 1 so the condition in the IF statement is false.
2. CALL HANOI (N −1, SOURCE, INTERMEDIATE, DESTINATION)
is encountered with A, B, and C as Ist, 2nd, and 3rd arguments.
Because this represents a recursive call, some stacking must be
done:
B (intermediate)
C (destination)
A (source)
L1 3 (N)
Return address stack Parameter stack
25
5. We reenter HANOI with N = 1, SOURCE=A, DESTINATION=C
and INTERMEDIATE=B. Because N = 1, the condition in the
IF statement is true.
6. Hence:
MOVE DISK FROM A TO C (1)
is output and a RETURN triggers a popping of a return address(L1)
and four parameters(N = 2, SOURCE=A,DESTINATION=B,
and INTERMEDIATE=C).
B (intermediate)
C (destination)
A (source)
L1 3 (N)
Return address stack Parameter stack
26
10. Because N = 1, the IF statement generates the output:
27
15. Reenter HANOI with N = 1, SOURCE = B, DESTINATION=A,
INTERMEDIATE=C. Because N = 1, output:
Unit II
Short Questions
29
3. Name some of the features of python.
Following are some of the salient features of python;
• It supports functional and structured programming methods as
well as OOP. ıtem It can be used as a scripting language or can
be compiled to byte-code for building large applications.
• It provides very high-level dynamic data types and supports dynamic
type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, ActiveX, CORBA, and
Java.
4. Mention the use of IDLE tool?
The IDLE tool offers a more efficient platform to write code and work
interactively with Python. We can access IDLE on the same folder
or the command line icon or on the start menu.
5. Explain the steps to exit from Python?
To exit from Python, you can type any of these commands:
• quit()
• exit()
Control-Z then press enter key.
6. Mention about the Python interpreter?
The Python interpreter is a program that runs the Python programs
we write.
7. Define a source code. What is byte code?
Source code is the statements we write for our program—it consists
of text in text files that normally end with a .py extension. Byte
code is the lower-level form of our program after Python compiles it.
Python automatically stores byte code in files with a .pyc extension.
30
8. Explain briefly about the Python Virtual Machine(PVM)?
The PVM is the Python Virtual Machine – the runtime engine of
Python that interprets our compiled byte code.
9. Mention the two ways of Using Python Interpreter?
Interactive mode - Interactive mode is a command line shell which
gives immediate feedback for each statement, while running previously
fed statements in active memory.
Script mode - A script mode can store code in a file and it uses the
interpreter to execute the contents of file.
10. Explain the steps involved to run a script from within IDLE?
Within the text edit window of the file we wish to run, we must
select the window’s Run→Run Module menu option. This runs the
window’s source code as a top-level script file and displays its output
back in the interactive Python shell window.
31
and multiple string types (simple strings and Unicode strings in
Python 2.X, and text strings and byte strings in Python 3.X).
14. List out the rules used for naming a variable in python.
• Variable names can only contain upper case (A-Z), lower case
(a-z) letters digits (0-9) and underscore characters.
• Variable names are case sensitive
• Numbers are allowed, but they should not be used at the beginning
of the variable name.
• Camel case notation or underscores can be used. Camel case is
the practice of writing compound words with mixed casing.
• No special symbols other than underscore are allowed.
• Reserved keywords cannot be used as a variable name
15. Describe the way to assign a value to a variable in python.
The equal sign (=) is used to assign values to variables. The operand
to the left of = operator is the name of the variable and the operand
to the right of = operator is the value stored in that variable. Syntax:
<variable name> = <value>
16. Define Keywords.
Keywords or reserved words are special commands that compiler/interpreter
understands and these reserve words cannot be used as a const variable,
or any other identifier names. There are 33 keywords.
17. Define Identifiers.
An identifier is a name used to identify a variable, function, class,
module or any other object. It helps differentiating one entity from
another.
18. Explain about “Immutable”, and mention the three Python’s
core types that are considered immutable.
32
An “immutable” object is an object that cannot be changed after
it is created. Numbers, strings, and tuples in Python fall into this
category. While we cannot change an immutable object in place, we
can always make a new one by running an expression. Byte arrays
in recent Pythons offer mutability for text, but they are not normal
strings, and only apply directly to text if it’s a simple 8-bit kind (e.g.,
ASCII).
19. Define multiline statement in Python.
A multiple line expression is a single statement by wrapping the lines
inside braces {},square brackets [ ] and parentheses ( ).
20. Write the syntax for the Python output function.
print("<expression>")
#multiple expressions
print("<expression>,<expression>")
print("<expression>",<variable name>)
describes what the source code has done. In Python, we use the
hash (#) symbol to start writing a comment Alternatively, use triple
single (''') or triple double quotes (""") at the start and end of a
multiple-line comment. Python interpreter ignores comment.
24. Define Operators and list its type.
An operator is a symbol that represents an operation performed
on one Or more operands. An operand is a quantity on which an
operation is performed Operators that take one operand are called
unary operators. A binary operator operates on two operands. Python
uses different operators. They are:
1. Arithmetic Operators
2. Relational or Comparison Operators
3. Assignment Operators
4. Bit wise Operators Logical Operators
5. Membership Operators
6. Identity Operators
25. Outline in a few words about bitwise operators in Python?
Bitwise operations are operations that directly manipulate bits. It
performs bit by bit operations. It returns binary coded output(Table:1).
35
Membership operators are used to test whether a value (variable) is
found in a sequence like string, list, tuple, set and dictionary. There
are two membership operators that are used in Python. They are:
• in: Evaluates to true, if it finds a variable in the specified sequence
and false otherwise
• not in: Evaluates to true if it does not finds a variable in the
specified sequence and false otherwise
30. Mention the use of identity operators.
Identity operators are used to compare the memory location of two
objects. It is used to check whether the two values (variables) are
located on the same part of the memory. The variables that are equal
doesn’t mean that, they are identical. The two identify operators
used in Python. They are:
• is: Evaluates to true, if the variables on either side of the operator
point to the same object and false otherwise.
• is not: Evaluates to false, if the variables on either side of the
operator point to the same object and true otherwise.
31. Explain briefly about operator precedence
The operator precedence determines which operators need to be
evaluated first. To avoid ambiguity in values, precedence operators
are necessary.
32. Define Associativity.
Associativity is the order in which an expression is evaluated, that
has multiple operator of same precedence. Almost all the operators
have left-to-right associativity. When two operators have the same
precedence, associativity helps to determine the order of operations.
33. List out the various advantages of Python.
36
• Dynamic Type Checking makes it inherently generic – C++ templates
for free
• Free, as in Open Source — free Portability
• Powerful language features and library
• Easy to use and learn
Tuple Assignment
35. Define a tuple? How literals of type tuple are written? Give
example.
A tuple is a sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists,
however, tuples are enclosed within parentheses. They are immutable.
Syntactically, they are normally coded in parentheses instead of square
brackets, and they support arbitrary types, arbitrary nesting, and the
usual sequence operations:–
37
36. Identify the meaning of “sequence” in python and which
three types are involved into this category?
A “sequence” is a positionally ordered collection of objects. Strings,
lists, and tuples are all sequences in Python. They share common
sequence operations, such as indexing, concatenation, and slicing,
but also have type-specific method calls. A related term, "iterable",
means either a physical sequence, or a virtual one that produces its
items on request.
37. Explain the role played by the translators in the programming
process?
Syntax error
Python Code messages
Syntax Checker
and Translator
Byte Code
Other error
User Inputs messages
Python Virtual
Machine (PVM)
Program
Outputs
Unit II
Big Questions
>>> bin_num=0b1010001
>>> print(bin_num)
81
>>> print(oct(bin_num))
42
0o121
>>> print(hex(bin_num))
0x51
>>> print(type(bin_num))
<class 'int'>
>>>
>>>name="Kannan"
>>>money=400
>>>print("%s took %d Rupees"%(name,money))
kannan took 400 Rupees
43
Table 3: Print Format Specifiers
Format Specifier Conversion
%c character
%s string formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERCAsE letters)
%e exponential notation (with lowercase ’e’)
%E exponential notation (with UPPER CASE ’E’)
%f floating point real number
>>> flag=True
>>> type(flag)
<class 'bool'>
Sequence A sequence is an ordered collection of items, indexed by
positive integers. It is combination of mutable and non mutable
data types. Three types of sequence data type available in Python
are Strings, Lists and Tuples Strings are already defined now we will
see about lists and tuples.
Lists: Lists are the most versatile of Python’s compound data types.
A list contains items separated by commas and enclosed within square
brackets ([]). To some extent, lists are similar to arrays in C. One
difference between them is that all the items belonging to a list can
be of different data type. The values stored in a list can be accessed
using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the list and working their way to end -1. The plus (+)
sign is the list concatenation operator, and the asterisk (*) is the
repetition operator. For example, consider the following script:–
list = ['abcd', 345 , 2.23, 'maya', 70.2]
tinylist = [123, 'maya']
44
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) #Prints elements starting from 2nd
till 4th
print(list[2:]) # Prints elements starting from 3rd
element
print(tinylist * 2) # Prints list two times
print(list + tinylist) #Prints concatenated lists
Output
['abcd', 345 , 2.23, 'maya', 70.2]
abcd
[345,2.23]
[2.23,'maya ',70.2]
[123,'maya ', 123,'maya']
['abcd', 345 , 2.23, 'maya', 70.2, 123,'maya']
Tuples
A tuple is another sequence data type that is similar to the list. A
tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed
in brackets ([ ]) and their elements and size can be changed, while
tuples are enclosed in parentheses (( )) and cannot be updated.
Tuples can be thought of as read-only lists. For example:–
tuple = ( 'abcd', 456 , 2.23, 'baba', 70.2)
tinytuple = (123, 'baba')
print(tuple) # Prints complete list of tuples
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd
till 3rd
print(tuple[2:]) # Prints elements starting from 3rd
element
print(tinytuple * 2) # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists
45
Output
('abcd', 456, 2.23, 'baba', 70.2)
abcd
(456, 2.23)
(2.23, 'baba', 70.2)
(123, 'baba', 123, 'baba')
('abcd', 456, 2.23, 'baba', 70.2, 123, 'baba')
Dictionary
Python’s dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
Dictionaries are enclosed by curly braces { } and values can be
assigned and accessed using square brackets []. For example :–
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name':'baba','code':6734, 'dept':'sales'}
print(dict['one']) # Prints value for ’one’ key
print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values
Output
This is one
This is two
{'dept':'sales','code':6734, 'name':'baba'}
['dept', 'code', 'name']
['sales', 6734, 'baba'])
46
a = int(input("enter a")
b = int(input("enter b")
print("a=",a,"b=",b)
a,b = b,a
print("a=",a,"b=",b)
>>>num = 85
>>>pi = 3.14159
47
>>> x=4+5j
>>> y=-8-2j
>>> xy=x+y
>>> print(xy) # This is a complex number
(-4+3j)
>>>print(type(num)) #This will return an integer
>>>print(type(pi)) #This will return a float
>>> print("x-y=",x-y)
x - y = 35
>>> print("x * y =",x*y)
x * y = 200
>>> print("x / y =",x/y)
x / y = 8.0
>>> print("x % z == ",x%z)
x % z == 1
>>> print("x**z=",x**z)
x**2= 64000
>>> print("x floor division z=",x // z)
x floor division z= 13
>>>
Relational or Comparison Operators
Comparison operators are used to compare values. It either returns
True or False according to the condition. It describes relation between
the left and right operands. They are also called as relational operator.
The following are the relational operators:–
Example
49
Table 5: Arithmetic Operators and their usage
Ope-
rator Explanation Example
+ Addition: It adds two operands or unary plus x+y
- Subtract right operand from the left or unary minus x - y or
-x - y
* Multiplication: It multiplies values on either side x * y
of operator
/ Division: It divides left hand operand by the right x / y
hand operand
% Modulus: It also divides left hand operand by right x % y
hand operand and returns the remainder
// Floor division: The division of operands where x // y
the result is the quotient in which the digits after
the decimal point are removed. But if one of
the operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity)
** Exponent: left operand raised to the power of right x ** y
Table 6: Relational Operators and their usage
Ope-
rator Explanation Example
> Greater than: True if left operand is greater than x>y
the right
< Less than: True if left operand is less than the right x <y
== Equal to:True if both operands are equal x == y
!= Not equal to: True if operands are not equal x != y
>= Greater than or equal to: True if left operand is, x >= y
greater than or equal to the right
Less than or equal to: True if left operand is less
<= than or equal to the right x <= y
50
>>> x,y=3,4
>>> print("x > y",x>y)
x > y False
>>> print("x < y",x<y)
x < y True
>>> print("x == y?",x == y)
x == y? False
>>> print("x+1<=y",x+1<=y)
x+1<=y True
>>> print("x+1>=y",x+1>=y)
x+1>=y True
>>> print("x != y",x!=y)
x != y True
>>> print("x==y?",x==y)
x==y? False
>>>
Assignment operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the
right to the variable a on the left. There are various compound
operators in Python like a += 5 that adds to the variable and later
assigns the same. It is equivalent to a = a + 5Example
>>> x,y=5,10
>>> x=y # y is in x as well
>>> print(x)
10
>>> print("x=",x)
x= 10
>>> x+=y #10+10=20 is the new value of x
>>> print("x=",x)
x= 20
>>> x-=y #20 – 10 = 10 is the new value of x
51
Table 7: Assignment Operators and their usage
Ope-
rator Explanation Example
It Assigns values from right side operands to x=y assigns the
= left side operand value of y to x
It adds right operand to the left operand and x+=y is equivalent
+= assign the result to left operand to x = x+y
It subtracts right operand from the left x-=y is equivalent
-= operand and assign the result to left operand to x = x-y
It multiplies right operand with the left x*=y is equivalent
*= operand and assign the result to left operand to x = x*y
It divides left operand with the right operand x/=y is equivalent
/= and assign the result to left operand to x = x/y
It takes modulus using two operands and x %=y is equivalent
%= assign the result to left operand
Performs exponential (power) calculation on x**=y is
**= operators and assign value to the left equivalent to x =
operand x**y
It performs floor division on operators and x//=y is equivalent
//= assign value to the left operand to x = x//y
>>> print("x=",x)
x= 10
>>> x*=y #10 * 10 = 100 is the new value of x
>>> print("x=",x)
x= 100
>>> x,y=3,10 #x is 3 and y is 10
>>> x/=y
>>> print("x=",x)
x= 0.3
>>> x,y=10,3 #x is 10 and y is 3
>>> x%=y #x is 10 % 3 remainder after
>>> print("x=",x)#dividing 10 by 3
52
x= 1
>>> x,y=10,3 #x is 10 and y is 3
>>> x//=y #quotient after dividing 10 by 3
>>> print("x=",x) #or x = x // y
x= 3
>>> x**=y #exponentiation
>>> print("x=",x)
x= 27
>>>
Example
>>> x,y=10,10
>>> print((x>=y) and (x ==y))
True
>>> x,y=10,5
>>> print((x>y) and (y>x))
False
>>> print((x>y) or (y>x))
True
>>> x=y
>>> print((x>y) or (y>x))
False
>>> print(not(x>y))
True
>>>
53
Membership Operators
Membership operators are used to test whether a value (variable) is
found in a sequence like string, list, tuple, set and dictionary. There
are two membership operators that are used in Python (in, not
in).Example
Table 9: Membership Operators and their usage
Ope-
rator Explanation Example
in Evaluates to true, if it finds a variable in x in y
the specified sequence and false otherwise
not in Evaluates to true if it does not finds a x not in y
variable in the I specified sequence and
false otherwise
Identity Operators
Identity operators are used to compare the memory location of two
objects. It is used to check whether the two values (variables) are
located on the same part of the memory. The variables that are equal
doesn’t mean that, they are identical. The two identity operators
used in Python are as follows:–
54
Example
Table 10: Identity Operators and their usage
Ope-
rator Explanation Example
Evaluates to true, if the variables on either
is side of the operator point to the same x is y
object and false otherwise.
Evaluates to false, if the variables on either
is not side of the operator point to the same x is not y
object and true otherwise.
>>> a='banana'
>>> b='banana'
>>> print(a == b)
True
>>> print(a is b)
True
>>> L=[1,2,3]
>>> M=L
>>> L == M
True
>>> L is M
True
>>> M = [1,2,3]
>>> M == L
True
>>> L is M
False
"banana" [1,2,3]
a M M [1,2,3]
>>> p,q,r,s,t=3,4,8,5,0
>>> t = (p+q)*r/s
>>> print(t)
11.2
>>> #(3+4)*8/5 = 7*8/5 = 56/5 = 11.2
>>>
6. Write a program in Python to calculate the distance between
the two points (x1, y1) and (x2, y2).
The formula for calculating the distance between the two points is:
p
distance = (y2 − y1)2 + (x2 − x1)2
We can write a Python script to determine the distance between the
two points (x1, y1) and (x2, y2) either by interactive or a scripting
method. In interactive method we can do as follows:
57
>>> x1=3
>>> y1=4
>>> x2=7
>>> y2=7
>>> distance=((y2-y1)**2+(x2-x1)**2)**0.5
>>> print(distance)
5.0
>>>
def distance(x1,y1,x2,y2):
u = x2-x1
v = y2-y1
dist = (u*u+v*v)**0.5
return dist
print(distance(3,4,7,7))
>>>
============= RESTART: /Users/bhaskar/python/distant.py ==
5.0
>>>
Thus the given python module returned the value of the distance
between the two points (3,4) and (7,7).
58
Unit III
Short Questions
• if statements
• if . . . else statements
• elif statements
• nested if . . . elif . . . else statements
• inline if
if expression : if expression1 :
statements1 statements1
el se : elif expression2 :
statements2 statements2
el se :
Listing 1: Syntax for if-else staements3
See Figure 20b
Listing 2: if-elif-else
59
Test True Test False
Expression False Expression
Statement Block
62
>>> class MyMinimalClass:
... pass
Place-holder for TODO work: We can also use it as a placeholder
for TODO work on a function or code that needs to be implemented
at a later point of time.
20. Write a program that accept a word from the user and
reverse it.
word = input("Input a word to reverse:")
for char in range(len(word)− 1, −1, −1):
print(word[char] , end="")
>>>greet('Govind')
Output:
68
• User-defined functions aid to crumble a big program into tiny
segments which formulates program simple to understand, sustain
and debug.
• If repetitive code occurs in a program, function be capable of
including those codes and execute when wanted by calling that
function.
• Programmers’ functioning on large project can partition the workload
by building different functions.
38. List the different structures of functions with variable number
of arguments.
• Python Default Arguments
• Python Keyword Arguments
• Required arguments
• Python Variable Length (Arbitrary) Arguments
39. Discuss the arguments passed in a Python method. They
are passed by value or by reference?
Every argument in a Python method is an Object. All the variables
in Python have reference to an Object. Therefore, arguments in
Python method are passed by Reference. Since some of the objects
passed as reference are mutable, we can change those objects in a
method. But for an Immutable object like String, any change done
within a method is not reflected outside.
40. Write the syntax for defining a function with keyword arguments.
70
A function is said to be an anonymous function when it is a defined
without a name. While normal functions are defined using the def
keyword, in Python anonymous functions are defined using the lambda
keyword for a short period of time. Lambda functions can have any
number of arguments but only one expression
Syntax: lambda arguments: expression
45. Write a program to illustrate the use of lambda function
with the built-in-function map().
# Program to double each item in a list using map()
old_list = [21, 25, 24, 27, 28, 31, 33, 42]
current_list = list(map(lambda number: number ∗ 2,old_list))
print( current_list )
Output:
[42, 50, 48, 54, 56, 62, 66, 84]
Another Example
sum lambda x, y: x + y
print("Sum=", sum(3, 5))
OUTPUT
Sum = 8
71
The slicing operator [:] is used to access a range of characters in a
string and to create substrings. The colon inside the square brackets
is used to separate two indices from each other Syntax
String_Variable [ start : finish −1]
Where, start: indicates the index of the initial character of the
substring finish: index of position after the substring to end
48. Given a string S with the value "s,pa,m", name two ways
to extract the two characters in the middle.
0 1 2 -3 -1
s , p a , m
[: :]
Figure 21: Offsets and slices: positive offsets start from the left end (offset
0 is the first item), and negatives count back from the right end (offset
–1 is the last item). Either kind of offset can be used to give positions in
indexing and slicing operations.
We can slice the string using S[2:4], or split on the comma and index
the string using S.split(’,’)[1]. Figure 21
49. Give an idea about replication operator.
A string or a group of strings may be repeated by using the exponential
operator (*) and a number to represent the number of times that the
string will be repeated. Here, * is the string replication operator
Syntax
(" String_variable " ∗ n)
Where, String_variable is the variable name, * is the string replication
operator, n is the number of times the string to be repeated.
50. Define Escape sequences.
72
Control characters are special characters that are not displayed on
the screen. Rather, they control the display of output. An escape
sequence is a character that gets interpreted when placed inside a
single or double quotes. They are usually represented as a backslash
notation (\).
51. Write a Python program to get the length of the string.
>>>string_a = 'Programming'
>>>len(string_a)
Lists as arrays
Unit III
Big Questions
Conditionals
74
If the Boolean expression evaluates to FALSE, then the next code
after the end of if statement will be executed. In Python, the body
of if statements were indicated by the indentation. It starts with an
indentation and ends with the first un-indented line. Refer Figure 20a.
at page 60
Example
number = int(input("Enter any number from the Keyboard: "))
if number> 50:
print ("Passed")
Output
Enter any number from the Keyboard: 60
Passed
Alternative if ... else Statement
An if ... else statement block first evaluates the ’if expression’.
If the test condition is TRUE, Python executes statements in the
body of the ’if statement’. Otherwise, if the condition is FALSE,
Python executes the statements in the else block. Refer Listing 1,
page 59
if test −expression:
statements #Run when text−expression is true
else:
statements #Run when text−expression is false
Example:
a, b = 100,200
if a > b: # 100 > 200
print("a is Greater than b")
else:
print("a is Less than b")
Output:
a is Less than b
75
Test
False
Expression
True
if elif False
Block Expression
True
elif Block
else Block
76
print("num is between 100 and 150")
else:
print("num is greater than 150")
Output:
num is greater than 150
>>>
Inline if statements
An inline if statement is a simpler form of if statement and is more
convenient, if we need to perform a simple task.
Syntax
do Task A if condition is true else do Task B
Example
>>>a = 2
>>>b = True
>>>a = 1 if b else None
"""This statement assigns 1 to a (Task A) if b is True.
Else it assigns None to a (Task B)"""
>>>a
1
2. Explain the syntax and flow chart of the following loop
statements
(i) for loops
(ii) while loop
For loops
The for loop is a simple and efficient way to step through all the
items in a sequence and run a block of code for each item in turn. For
loop iterates over a sequence that may have different data types such
as the list, tuple and string. It can also iterate any other objects that
may be defined in Python. The for-in loop repeats a given block
of codes by specified number of times. Syntax
77
for each
item in Enter while loop
sequence
Last
Yes Test False
item
Expression
reached?
No True
Output
0 1 2 3 4
80
Output 2
While Loop
While loop is used when we need to repeatedly execute a statement
or group of statements, while the test condition is True. When the
test condition is no longer true, program control passes to the line
after the loop.
Syntax
while Boolean−expression:
Statement 1
Statement 2
...
Statement n
Program 1
# Program to print the numbers from 0 to 4
counter = 0
while(counter < 4):
print('Count is : ' , counter)
counter = counter + 1
print ("Exit of the loop!")
Output
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Exit of the loop!
Explanation In the above program, when the text Enter the upper
limit appears, 5 is given as the input. i.e., n = 5. Initially, a counter i
is set to 1 and sum is set to 0. When the condition is checked for the
first time i <= n, it is True. Hence the execution enters the body of
while loop. Variable sum is added with i and i is incremented. Since
the next statement is un-indented, it assumes the end of while block
and again go back to check the condition. This process is repeated
until the condition given in the while loop is False and the control
goes to the next print statement to print the sum.
NESTED LOOPS
Nesting is defined as the placing of one loop inside the body of
another loop. When we "nest" two loops, the outer loop takes control
of the number of complete repetitions of the inner loop. While all
types of loops may be nested, we can have nested loops for both while
and for loops.
Syntax for nested for loop
82
Syntax for nested while loop
while test_expression:
while test_expression:
Statement(s)
Statement(s)
Program 1
Enter a Limit:30
1 2 3 5 7 11 13 17 19 23 29
Range or
other True
Expressions
Rest of
if False
for / while
Condition?
iterations
False
True
break
num = num + 1
print("End of Program")
Enter when to break(n<10):4
0 1 2 3 End of Program
Explanation
"if (num == breakn): break" will run the "break" command if num
is 4, the break statement will exit from the while loop, and run
"print(End of Program")
The continue statement
The continue statement causes an immediate jump to the top of a
loop(figure 25). It also sometimes lets us avoid statement nesting.
The next example uses continue to skip odd numbers. This code
prints all even numbers less than 10 and greater than or equal to
85
Enter
while
or for
loop
Range or
other True
Expressions
Rest of
if False
for / while
Condition?
iterations
False
True
continue
87
statement with no arguments is same as return None. Syntax
def functionname(parameters):
"""function_docstring"""
function suite
return[expression ]
By default, parameters have a positional performance and it is compulsory
to enlighten them in the similar order that they were defined. Program
def Greeting(name = "Everyone"):
""" Greeting the person """
print("Hai " + name + "!")
Greeting("Sai")
Greeting ()
Output
Hai Sai!
Hai Everyone!
FUNCTION CALL
Once a function has been defined, it is feasible to call it from another
function, program or even the python prompt. A function can be
called by simply type the function name with suitable arguments.
>>>Greeting ('Sai')
Hai, Sai!
Name of function
inputs
colon
89
variables because they may get altered by mistake and then result in
erroneous output.
num1 = 10 #global variable
print("Global variable num1 = ", num1)
def func(num2): # num2 is function parameter
print("In Function − Local Variable num2 = ",num2)
num3 = 30 #num3 is a local variable
print("In Function − Local Variable num3 = ",num3)
func(20) #20 is passed as an argument to the function
print("num1 again = ", num1) #global variable is being accessed
#Error− local variable can't be used outside the function in which
#it is defined
print("num3 outside function = ", num3)
Output
90
def display (str_a, int_x, float_y) :
print('The string is : ' ,str_a)
print('The integer value is : ' ,int_x)
print('The floating point value is : ' ,float_y)
display (float_y = 56789.045, str_a = 'Hello' , int_x =1234)
OUTPUT
The string is : Hello
The integer value is : 1234
The floating point value is: 56789.045
>>>
Default Arguments
Python allows users to specify function arguments that can have
default values. This means that a function can be called with fewer
arguments than it is defined to have. That is, if the function accepts
three parameters, but function call provides only two arguments,
then the third parameter will be assigned the default (already specified)
value. The default value to an argument is provided by using the
assignment operator (=). Users can specify a default value for one
or more arguments.
Example
def display (name, course = "BTech"): # Default Argument for course
print("Name : " + name)
print("Course : ", course)
display (course = "B.E", name = "Jegan") # Keyword Arguments
display (name = "Nabin")
OUTPUT
Name : Jegan
Course : B.E
Name : Nabin
Course : BTech
>>>
91
In the above code, the parameter name does not have a default value
and is therefore mandatory. That is, we must specify a value for
this parameter during the function call. But, parameter, course has
already been given a default value, so it is optional. If a value is
provided, it will overwrite the default value and in case a value is
not specified during function call, the one provided in the function
definition as the default value will be used.
Variable-length Arguments
In some situations, it is not known in advance how many arguments
will be passed to a function. In such cases, Python allows programmers
to make function calls with arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable-length arguments, then
the function definition uses an asterisk (*) before the parameter
name. Syntax for a function using variable arguments can be given
as,
def functionname([argl , arg2, .... ] ∗var_args_tuple ):
function statements
return [expression ]
def func(name, ∗fav_subjects):
print("\n", name, " likes to read ")
for subject in fav_subjects :
print(subject)
func("Narayanan", "Mathematics", "Android Programming")
func("Neeraja", "Machine Learning", "Data Structures", "Design and An
func("Mittal")
OUTPUT
Narayanan likes to read
Mathematics
Android Programming
Neeraja likes to read
Machine Learning
Data Structures
92
Design and Analysis of Algorithms
Mittal likes to read
>>>
Enter an integer: 4
The double of 4 is 8
Enter an integer: 8
The double of 8 is 16
Enter an integer: 10
The double of 10 is 20
Enter an integer:
Traceback (most recent call last):
File "/Users/bhaskar/Documents/Python/infiniteloop.py", lin
n = int(input("Enter an integer: "))
93
KeyboardInterrupt
>>>
Output
The sum is 55
>>>
Enter a vowel: t
94
That is not a vowel. Try again!
Finally, a Vowel has been Entered!
Enter a vowel: u
>>>
Loop with condition at bottom This kind of loop ensures that
the body of the loop is executed at least once. It can be implemented
using an infinite loop along with a conditional break at the end. This
is similar to the do...while loop in C.
#Program To illustrate a loop with condition at the bottom
num1, num2 = 6, 3
choice = 1
print(num1,num2)
while choice != 5:
print("Menu")
print("l . Addition")
print("2. Subtraction")
print("3. Multiplication ")
print("4. Division ")
print("5. Exit")
choice = int(input("Enter your choice:"))
if choice == 1: print ("Sum=", (num1 + num2))
if choice == 2: print ("Difference =", (num1 − num2))
if choice == 3: print ("Product=", (num1 ∗ num2))
if choice == 4: print ("Quotient=", (num1 / num2))
if choice == 5:
break;
print("End of Program")
Output
6 3
Menu
l. Addition
2. Subtraction
95
3. Multiplication
4. Division
5. Exit
Enter your choice:1
Sum= 9
End of Program
Menu
l. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice:2
Difference = 3
End of Program
Menu
l. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice:5
>>>
>>> S='spam'
>>> result=S.find('pa') # call function to find 'pa' in S
>>> result
1
96
Function Description Example
Capitalizes first letter of >>> S='maria'
capitalize()
string >>> S.capitalize()
'Maria'
False
1581374
>>>
1 5 8 13 7 4
concatenate()
1581374
98
routes, analyzing language, and crawling links on the Web, for example.
Recursion is even an alternative to simple loops and iterations, though
not necessarily the simplest or most efficient one. Let’s look at the
following example:
def countdown(n):
if n <= 0:
print(' Blastoff ! ' )
else:
print(n)
countdown(n−1)
If n is 0 or negative, it outputs the word, "Blastoff!" Otherwise,
it outputs n and then calls a function named countdown – itself –
passing n -1 as an argument. What happens if we call this function
like this?
>>> countdown(5)
99
5
4
3
2
1
Blastoff!
>>>
>>> M=[[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>
Here, we’ve coded a list that contains three other lists. The effect
100
is to represent a 3 × 3 matrix of numbers. Such a structure can be
accessed in a variety of ways:
The first operation here fetches the entire second row, and the second
grabs the third item within that row (it runs left to right, like the
earlier string strip and split). In addition to sequence operations and
list methods, Python includes a more advanced operation known as
a list comprehension expression, which turns out to be a powerful
way to process structures like our matrix.
13. Create a program to reverse a string without using any
built-in functions
There are various ways to reverse a string in python. Let us see
a few:
def reverse1(s) : def reverse2(s) :
str1 = "" if len(s) == 0:
return s
for i in s : else:
str1 = i + str1 return reverse2(s [1:]) + s[0]
return str1
Listing 4: using recursion
Listing 3: reverse using loop
In above code Listing 3, we call a function reverse1 to reverse a
string, which iterates to every element and intelligently join each
character in the beginning so as to obtain the reversed string. Similarly
in Listing 4, the string is passed as an argument to a recursive
function reverse2 to reverse the string. In the function, the base
condition is that if the length of the string is equal to 0, the string
is returned. If not equal to 0, the reverse function is recursively
101
called to slice the part of the string except the first character and
concatenate the first character to the end of the sliced string.
14. Illustrate a program to find GCD of m and n.
m = int(input("Enter a number:"))
n = int(input("Enter another number:"))
rem = m % n
while rem != 0 :
m=n
n = rem
rem=m % n
print ("gcd of given numbers is :", n)
102
f (x)
f (x) = x2 − 3
f (x0 )
f (x1 )
α
x
x1 x0
Unit IV
Short Questions
list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters
1. Define a list
104
Lists are the simplest data structure in Python and are used to
store a list of values. It is an ordered sequence of values of any
data_type (string, float, integer, etc.,). Values in the list are called
elements/items. These are mutable and indexed/ordered.
2. Describe the way to slice a list in python.
The values stored in a list can be accessed using slicing operator,
the colon (:) with indexes starting at 0 in the beginning of the list
and ending with -1. It is used to access a range of elements on lists.
Syntax
list_name[start:finish-1]
3. Explain about how to concatenate a list in python.
It is possible to concatenate or combine two or more lists in Python
with the (+) operator. The (+) sign is the list concatenation operator.
4. Explain about how to repeat a list in python.
To repeat a list, we can use the(*)operator and a number to specify
the number of times the list to be repeated. Here the asterisk (*)
sign is the repetition operator.
5. Determine the output of print(list[0])if
list = [’abcd’,29,2.23,’john’,70.2]?
It will print first element of the list. Output would be abcd.
6. Determine the output of print(list[1:3]) if
list = [’abcd’,23,2.23,’john’,70.2]?
It will print elements starting from 2nd till 3rd. Output would be
[23, 2.23].
7. Consider the following three statements. Do they change
the value printed for A?
A = "spam"
B = A
B = "shrubbery"
105
No: A still prints as "spam". When B is assigned to the string
"shrubbery", all that happens is that the variable B is reset to point
to the new string object. A and B initially share (i.e., reference/point
to) the same single string object "spam", but two names are never
linked together in Python. Thus, setting B to a different object has
no effect on A. The same would be true if the last statement here
were B = B + ’shrubbery’, by the way – the concatenation would
make a new object for its result, which would then be assigned to B
only. We can never overwrite a string (or number, or tuple) in place,
because strings are immutable.
8. Consider these three statements. Do they change the printed
value of A?
A = ["spam"]
B = A
B[0] = "shrubbery"
Yes: A now prints as ["shrubbery"]. Technically, we haven’t really
changed either A or B; instead, we’ve changed part of the object
they both reference (point to) by overwriting that object in place
through the variable B. Because A references the same object as B,
the update is reflected in A as well.
9. Determine the output of print(list[2:]) if
list = [’abcd’,786,2.23,’john’,70.2]?
It will print elements starting from 3rd element. Output would be
[2.23, ’john’, 70.2].
10. Determine the output of print(tinylist * 2) if
tinylist = [123,’john’]?
It will print list two times.Output would be [123,’john’,123,’john’]
11. Determine the output of print(list + tinylist * 2) if
list = [ 'abcd',786,2.23,'john',70.2] and
tinylist = [123,'john']?
106
It will print the concatenated lists. Output would be
['abcd',786,2.23,'john',70.2,123,'john',123,'john']
12. Define append() and extend().
Lists are mutable, hence we can easily add an element or a range
of elements on a list with the append() or extend() method. The
append() method is used to add a single item while the extend()
method is used to append two or more items. Both methods are
used to add items at the end of the original list.
Syntax
list_name.append(object) # Append method
list_name.extend(seq) # Extend method
13. Describe the way to remove an item from the list in python.
To remove an item from a list, we can use either the remove() or
the pop() method.
• remove() method
The remove() method removes the specified item.
Syntax
list_name.remove(object)
107
15. Explain map() with an example.
The function applies a passed-in function to each item in an iterable
object and returns a list containing all the function call results.
Example
str= input("Enter a list :")
lis =list(map(int,str.split() ))
print( lis )
Output
0 Python
108
1 Java
2 C++
23. Mention the steps to get all the keys from the dictionary
Using dictionary.keys() function, we can get all the keys from the
dictionary object. print dict.keys() #Prints all the keys
24. Mention the way to get all the values from the dictionary
Using dictionary.values() function, we can get all the values from the
dictionary object. print dict.values() # Prints all the values
25. Distinguish between mutable and immutable objects?
Objects whose value can change are said to be mutable and objects
whose value is unchangeable once they are created are called immutable.
An object’s mutability is determined by its type.
109
26. Define reduce() in Python.
It takes a binary function and some list of values and typically
produces a single value: it reduces or accumulates these results into a
single value. Unlike map and filter (which are defined and automatically
imported from the built-ins module) we must import reduce from the
functools module explicitly. Syntax
r = reduce(function, sequence)
27. Define list comprehension.
List comprehensions are a tool for transforming one list (any iterable
actually) into another list. List comprehensions provide an alternative
syntax to creating lists and other sequential data types. While other
methods of iteration, such as for loops, can also be used to create
lists, list comprehensions may be preferred because they can limit
the number of lines used in our program.
Syntax
[ expression for item in list if conditional ]
Lists
List methods
Example 1.
num_list = [0, 5, 10, 15, 50, 14) # List with integers
string_list = ["cat", " lion ", " tiger ", "zebra"] # Strings
# List with mixed data types
mixed_list = [18, " publishers ", 35.5]
# List with nested list
nested list = ["keyboard", 8.5, 6, [5, 1, 3, 4, 5.5, 2]]
Example 2.
First_year = ["English", "Chem", "Phys", "Math", "Python"]
112
Table 12: List Indexing and its contents
Index 0 1 2 3 4
String English Chem Phys Math Python
113
arguments. When the index is less than the length of the list, this
method places the new element before the existing element at that
index, after shifting elements to the right by one position. At the end
of the operation, the new element occupies the given index position.
When the index is greater than or equal to the length of the list, the
new element is added to the end of the list. Example 3 shows insert
in action:
Example 3.
>>> example = [1, 2)
>>> example
[1, 2)
>>> example.insert(1, 10)
>>> example
[1, 10, 2)
>>> example.insert(3, 25)
>>> example
[1, 10, 2, 25)
>>>
115
When using a list, we can change its contents by assigning to either a
particular item (offset) or an entire section (slice). Consider Example 6:
Example 6.
>>> L = ['spam', 'Spam', 'SPAM!']
>>> L[1] = 'eggs'
>>> L
['spam', 'eggs', 'SPAM!']
>>> L[0:2] = ['eat','more']
>>> L
['eat', 'more', 'SPAM!']
>>>
2. Explain in detail about cloning
Consider the following example,
def removeDups(L1, L2):
"""Assumes that L1 and L2 are lists . Removes any element from
L1 that also occurs in L2"""
for e1 in L1:
if e1 in L2:
L1.remove(e1)
print(e1)
L1 = [1,2,3,4]
L2 = [1,2,5,6]
removeDups(L1, L2)
print('L1 =', L1)
Output
1
3
4
L1 = [2, 3, 4]
>>>
116
Explanation During a for loop, the implementation of Python
keeps track of where it is in the list using an internal counter that
is incremented at the end of each iteration. When the value of the
counter reaches the current length of the list, the loop terminates.
This works as one might expect if the list is not mutated within the
loop, but can have surprising consequences if the list is mutated. In
this case, the hidden counter starts out at 0, discovers that L1[0] is
in L2, and removes it – reducing the length of L1 to 3. The counter
is then incremented to 1, and the code proceeds to check if the value
of L1[1] is in L2. Notice that this is not the original value of L1[1]
(i.e., 2), but rather the current value of L1[1] (i.e., 3). As we can see,
it is possible to figure out what happens when the list is modified
within the loop. However, it is not easy. And what happens is likely
to be unintentional, as in this example.
One way to avoid this kind of problem is to use slicing to clone –
(i.e., make a copy of) the list and write for e1 in L1[:]. Notice that
writing
newL1 = L1
for e1 in newL1:
would not solve the problem. It would not create a copy of L1, but
would merely introduce a new name for the existing list. Slicing is
not the only way to clone lists in Python. The expression list(L)
returns a copy of the list L. If the list to be copied contains mutable
objects that we want to copy as well, import the standard library
module copy and use the function copy.deepcopy.
3. Explain how to add, modify and delete elements from a
dictionary.
Creating a dictionary
A dictionary may contain any data type and is mutable. Its keys,
however, are immutable and can only be a string, tuple, or a number.
Values stored on a dictionary can only be accessed through the keys.
Syntax
117
dict = {} # To create an empty dictionary :
# To create a dictionary with key−value pairs :
dict = {keyl: valuel , key2:value2 , key3:value3 , key4:value4}
Where, dict is the dictionary name
key - User defined variable names
value – Values assigned for the key
Example 1.
member_1 = {'Name': 'MaduraiPublishers', 'price' :400, 'Telephone No.':0452-1234567}
Output
'Mary'
89.5
119
Output {'Ranking': '3rd', 'Name': 'Mary',
'Average': 89.5, 'Age': 24}
Removing or Deleting Elements from a Dictionary To remove
a key: value pair from a dictionary, we can use the pop() method
which removes the pair and returns the value of the given key.
(a) pop() method The pop() method is used to remove a specified
key-value pair from a dictionary and return the value of the
deleted key.
Example 2.
>>>my_dict = {'ocean' : 'Indian Ocean' , \
'Sea' : 'Arabian','river': 'Cauvery',\
'swamp':' Everglades'}
# To remove the key 'river' and its value:
>>>my_dict.pop('river')
>>>my_dict # Updated Dictionary
Output
'Cauvery'
{'Sea': 'Arabian', 'swamp': 'Everglades',
'ocean': 'Indian Ocean'}
(b) popitem() method The popitem() method is used to remove a
random key-value pair from a dictionary. The method does not
take any argument and returns the deleted key-value pair.
Program 5.
>>>my_dict {'ocean' : 'Indian Ocean' , 'Sea' : 'Arabian' ,
,'river' :'Cauvery', 'swamp':' Everglades'}
>>>my_dict.popitem()
('swamp', 'The Everglades')
# Here's what's left of my_dict:
>>>my_dict
120
Output
{'ocean': 'Indian Ocean', 'river': Cauvery,
'Sea': 'Arabian'}
(c) clear() method The clear() method is used to remove all key-value
pairs in a dictionary.
>>>my_dict.clear()
>>>my_dict
Output
{} # Empty Dictionary
(d) Deleting a Dictionary The del keyword is used to delete a
dictionary.
Syntax
del dict_name
Program 6.
# To delete the my_dict dictionary, we will use the del ke
>>> my_dict={'a':1,'b':2}
>>> my_dict
{'a': 1, 'b': 2}
>>> del my_dict
>>> my_dict
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
my_dict
NameError: name 'my_dict' is not defined
>>>
4. Write a program to sort an array of numbers using selection
sort.
def selectionSort ( alist ) :
counter = 0
for currentPosition in range(len(alist)−1, 0, −1):
maxValue = alist[ currentPosition ]
maxPosition = currentPosition
121
exChange = False
for index in range(0, currentPosition ) :
if alist [ index ] > alist [maxPosition]:
maxPosition = index
maxValue = alist[ index ]
alist [maxPosition], alist [ currentPosition ] = alist [ currentPosition ], alist [m
123
addition, accessing an index with a noninteger numeric type will
raise a NameError.
Syntax
my_tuple = [index] # To access tuple items
# Create new_tuple with strings as elements:
new_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e')
>>>new_tuple[0] # To access the first element
'p'
>>> new_tuple[7] # To access the 7th element
'm'
>>>new tuple # To print the original list
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e')
Negative Indexing It is a sequence type, we can access tuples
through negative indexing. The last "term takes the -1 index,
the penultimate item the -2 index, and so on.
>>>new_tuple[-l] # To access the last item
'e'
>>>new tuple[-7] # To access the -7th element
'g'
Index# 0 1 2 3 4 5 6 7 8
String p r o g r a m m e
Negative -9 -8 -7 -6 -5 -4 -3 -2 -1
index
Slicing a Tuple
The slicing operator (:) is used to access a range of items in a tuple.
Syntax tuple_name [start : finish-l]
Where, tuple_name is the user-defined name for the string start
indicates the index of the initial character of the substring finish
indicates the index of the ending character of the substring
124
Program 2. # Create new_tuple with strings as elements:
>>> new_tuple = ('i','m','m','u','t','a','b','1','e')
# To access the elements on the 4th to the 6th index:
#4 is the index of the first item and 7 is the index of the
#first item to be excluded.
>>> new_tuple[4:7]
# To access tuple elements from index 2 to the end:
>>> new tuple[2:]
# To access tuple items from the beginning to the 3rd index:
>>> new_tuple[:4]
Output
Output
tupl[0]: physics
up2[1:5]: (2, 3, 4, 5)
Output
(12, 34.56, 'abc', 'xyz')
After deleting tup
Traceback (most recent call last):
File "/test1.py", line 9, in <module>
print(tup)
NameError: name 'tup' is not defined
>>>
126
Tuple Membership Test To test if a tuple contains a specific item,
we can use the membership operators in and not in.
Example 2.
>>>tuple_1 = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e')
>>>'g' in tuple_1
>>>'1' in tuple_1
>>>'e' not in tuple_1
>>>'x' not in' tuple_1
Output
True
False
False
True
Tuple Methods
In Python, count() and index() are the two methods that work
with tuples.
(a) Count(x)
The count() returns the number of elements which is equal to the
given element. Syntax
mytuple.count('character')
Program 5.
>>>new tuple = ("p","r","a","g","r","a","m","m","e","r")
>>>new_tuple.count('m')
>>>new_tuple.count('r')
Output
2
3
127
(b) Index(x)
It returns the index of the first element which is equal to the
given element.
Syntax
mytuple.index('character')
Program 6.
>>>new tuple = ("p","r","o","g","r","a","m","m","e","r")
>>>new_tuple.index('m')
>>>new_tuple.index('r')
Output
6
1
Built-in Functions with Tuples
Several built-in functions are often used with tuple to carry out
specific tasks. Here are the functions that we can use with a
tuple.
len()
It returns the number of elements on a tuple.
>>> tuple_one = ('cat','dog','lion','elephant','zebra')
>>> len(tuple_one)
Output
5
(c) max()
It returns the largest element on a tuple.
>>>numbers_tuple = (1, 5, 7, 9, 10, 12)
>>>max(numbers_tuple)
Output
12
When a tuple holds items of purely string data type, max()
128
evaluates the items alphabetically and returns the alphabetically
largest item.
>>>my tuple = ('car','zebra','book','hat','shop','art')
>>>max(my_tuple)
Output
'zebra'
Using max() on tuples with mixed data types (string and numbers)
will raise a TypeError due to the use of unorderable types.
(d) min()
It returns the smallest element on a tuple.
>>>numbers_tuple = (1, 5, 7, 9, 10, 12)
>>>min(numbers_tuple)
Output
1
When used on a tuple that contains purely string data type min()
evaluates the items alphabetically and returns the alphabetically
first item.
>>>my_tuple = ('car','zebra','book','hat','shop','art')
>>>min(my_tuple)
Output 'art'
(e) sorted()
It returns a sorted list but it does not sort the tuple itself. The
order of elements inside the tuple remains unchanged.
>>>my_tuple = ('dog','bird','ant','cat','elephant')
>>>sorted(my_tuple)
# The order of elements inside the my_tuple however,
#remains the same
>>>my_tuple
Output
129
['ant', 'bird', 'cat', 'dog', 'elephant']
('dog', 'bird', 'ant', 'cat', 'elephant')
(f) sum()
It returns the total of all items on a tuple.
Example 3.
>>>my_tuple = (5, 10, 15, 20, 25, 30)
>>>sum(my_tuple)
Output
105
(g) tuple()
It converts iterables like string, list, dictionary, or set to a tuple.
How to convert a string to a tuple
>>>tuple("Programmer")
Output
('P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r')
Example 4.
>>>my_string = ("Hello World")
>>>tuple(my_string)
Output
('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
Converting a dictionary to a tuple
Example 5.
>>>tuple({'Name' :'Joshua', 'Animal':' elephant', 'Color': 'blue', 'Age': 22})
Output
('Age', 'Color', 'Name', 'Animal')
Example 6.
my_dict = {'Name' : 'Joy', 'Area':' Madurai' , 'subscription' : 'premium' }
>>>tuple(my_dict)
130
Output
('Name', 'Area', 'subscription')
Converting a list to a tuple
Example 7.
>>>tuple(['red', 'blue', 'yellow', 'green', 'orange', 'violet'])
Output
('red', 'blue', 'yellow', 'green', 'orange', 'violet')
Example 8.
>>>my_list = ['interest','rate','principal','discount','rollover']
>>>tuple(my_list)
Output
('interest', 'rate', 'principal', 'discount', 'rollover')
(h) Enumerate()
It returns an enumerate object containing the value and index of
all tuple elements as pairs
Example 9.
>>>my_tuple = (1, 3, 5, 7, 9, 11, 13, 15)
>>>enumerate(my tuple)
Output <enumerate object at 0x105bbb410>
7. Illustrate the ways of creating the tuple and the tuple assignment
with suitable programs
Relevant points from Question Number 6
8. Illustrate List Comprehension with suitable examples
We can create a 3 × 3 matrix using lists as shown below:
>>> M=[[1,2,3],[4,5,6],[7,8,9]]
>>> M
[[1,2,3],[4,5,6],[7,8,9]]
131
Here, we?ve coded a list that contains three other lists. The effect
is to represent a 3 × 3 matrix of numbers. Such a structure can be
accessed in a variety of ways: >>> M[1]. #get row 2
[4,5,6] #get row 2 and then item 3
Output
Program 2.
132
# initializing tuples
test_tup1 = ('KLN', ' is ' , ' best ' )
test_tup2 = (1, 2, 3)
# printing result
print("Dictionary from tuples : " + str(res))
Output
133