0% found this document useful (0 votes)
18 views

Unit - 1 INTRODUCTION TO PYTHON - ECE

Uploaded by

Mohan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit - 1 INTRODUCTION TO PYTHON - ECE

Uploaded by

Mohan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

UNIT I

INTRODUCTION TO PYTHON
Structure of Python Program – Underlying mechanism of Module Execution – Branching and
Looping – Problem Solving Using Branches and Loops – Functions – Lambda Functions –
Lists and Mutability – Problem Solving Using Lists and Functions.

The Structure of Python Programs


The structure of a Python program consists of a set of statements. Each statement can
contain one or more mathematical expressions, and each expression consists of literals,
identifiers and operators.

Python runs a program by executing its statements, each of which fulfills a specific
functionality.
All statements are executed in a fixed and mechanical way.
Example
Take the assignment statement. The right-hand side of = must be an
expression, and the left-hand side must be an identifier.
(Assignment Statement)
X = 10+20
Identifier Expression

The statement is executed by evaluating the expression first, and then binding
the resulting object with associating the left-hand-side identifier.

Table 3.1 Literals or Data Types

Table 3.2 Operators


Table 3.3 Summary of Statement

Each expression is evaluated into a single object during program execution. An


expression is evaluated by applying operators to operands, which can be literals or identifiers.
Operators are applied according to a fixed precedence, and brackets can be used to explicitly
specify the order of evaluation. Table 3.2 give a summary of all the operators that have been
introduced, which include arithmetic operators (+, -, * etc.), the dot (.) operator, the indexing
operator ([ ]) and the function call operator (()). Their precedence is as follows. The dot,
indexing and function call operators have higher precedence than the arithmetic operators,
while ** has higher precedence than *, /, // and % in arithmetic operators. Operators with the
same precedence are executed from left to right.
Both identifiers and literals represent Python objects in the underlying
implementation. Each Python object is associated with a type. Two categories of types have
been introduced in this book, including numbers (int, float, long, complex) and strings. While
numbers are essential for mathematical computation, strings are useful for text input and
output functionalities. A list of the types that have been introduced and their corresponding
literals is shown in Table 3.1.

Comments: In addition to statements, a Python program can also consist of


comments. Comments are not executed when a Python program is executed, but they are
useful for making Python programs more readable. It is a good habit to write comments when
programming, since proper comments can not only help other programmers understand the
design of a program, but also remind a programmer of her own thinking when designing the
program. Comments are particularly important in large software projects.
Python comments start with a # symbol. In a line of Python code, all the texts after the
first # symbol are treated as comments, and ignored during execution.
>>> g=9.81 # the gravity constant
>>> y=g #+1
>>> print y #*2#*3
9.81
In the example above, the first line contains some comments that explain the purpose
of the identifier g. The comments are useful for the understanding of subsequent uses of the
identifier. The second line in the example above illustrates another use of comments, which is
to temporarily delete a part of Python code. In this example, the value of y is 9.81, rather than
10.81, since the text ‘+1’ is placed after a # symbol. In this case, the programmer might have
started with the statement y = g + 1, but then decided to try y = x instead. She, however, does
not want to completely remove the ‘+1’ part, since there is a chance that she wants to add it
back after some testing. Therefore, she chooses to keep ‘+1’ in the line but as a comment. In
programming terminology, she commented out the part of code. The last line above contains
two # symbols. It prints 9.81 on the console, but not 19.62 or 29.43, because all the text
after the first # symbol are treated as comments.
Comments can also be written as a single line, with the # symbol at the beginning of
the line. This form of comment is called in-line comment. In contrast, comments after a
statement is called an end-of-line comment. In-line comments are typically used to explain
the design of a set of multiple statements under the comment line.
Combined Statements. Multiple Python statements can be written in a single
line, separated by semi-colons (;)
>>> a=1;b=2; print a #three statements combined
1
>>> b
2
Such combinations offer compactness in code, but can make programs more difficult to
understand.

The Underlying Mechanism of Module Execution

Module Objects
First, it has been introduced in the previous chapter that an imported module can be
accessed by an identifier that bares the same name of the module (i.e. math). In addition,
constants and functions defined in a module can be accessed by using the module name and
the dot (.) operator (i.e. math.e). The former functionality is achieved by registering the name
of the module in the binding table. To achieve the latter functionality, an imported module is
associated with a binding table of its own, which contains the names of constants and
functions defined in the module. For example, the memory structure after the following three
lines of code are executed is shown in Fig. 3.4.
>>> x = 1
>>> y =’abc’
>>> import math
There are three identifiers in the main binding table: x, y and math. While x and y are put into
the binding table by the corresponding assignment statements, math is inserted by the import
statement. x and y are associated with the objects 1 and ‘abc’, respectively. math, in contrast,
is associated with a binding table, which contains the constants and functions defined in the
math module.
The dot (.) operator syntactically connects a module name identifier to a second
identifier (e.g. math.e). The <module>.<identifier> expression is evaluated to the value of
identifier, looked up in the binding table of module. For example, when the expression math.e
is evaluated, Python first looks for the name math in the main binding table. If it is found,
Python follows the corresponding link to find the binding table of math, in which is searches
for the identifier e. In each of the two look-ups, if the corresponding identifier is not found,
an error will occur.

Fig 3.4 Module name and binding table


1. >>> import math
>>> math.e
2.718281828459045
2. >>> math.e1
Traceback ( most recent call last):
File"<stdin >", line 1, in <module >
AttributeError: ’module ’ object has no attribute ’e1’
2. >>> math1.e
Traceback ( most recent call last):
File "<stdin >", line 1, in <module >
NameError: name ’math1 ’ is not defined
In the example above, the second command (math.e) successfully returns the value of
math.e, since math has been imported to the current binding table and e is a part of the math
binding table. However, the third command (math.e1) raises an error because the name e1 is
not in the math binding table, and the fourth command (math1.e) raises an error because the
name math1 is not in the current binding table.
In Python, the dot (.) operator indicates a binding table, specified by the left operand.
An identifier is looked up in the specified binding table if it is the right operand of a dot
operator (e.g. math.e), but in the current binding table otherwise (e.g. e). The main binding
table of IDLE or a Python program is also called the global binding table.

Library Modules
The Python modules that have been introduced in this book are used as libraries,
which are assemblies of code that provide specific functionalities for reuse. Most Python
Library modules are nothing but normal Python programs, typically stored in a specific
library path in the file system. The random module, for example, is a Python program that
can be found on a Linux or Mac OS at:
/usr/lib/python2.7/random.py
and on a Windows system at:
C:\Python27\Lib\random.py
Most libraries provided by the Python distribution are located in the folders above. In
addition to the Python distribution itself, libraries can also be downloaded from a third party.
For example, the SciPy toolkit contains libraries for many scientific computation
functionalities.1 After installation, such libraries are typically located on a Linux or Max OS
at:
/Library/Python/2.7/ site - packages/
and on a Windows platform at:
C:\Python27\Lib\site – packages\
Python automatically searches for the locations above when a library module is
imported, where the folder names depend on the Python version. Note that the math module
is an exception: it cannot be found under the library folder locations above. This is because
math is a very commonly used module, and is built in the main Python program itself. Other
commonly used modules, including cmath, are also built-in.

Making Use of Libraries. Before writing one’s own code for a specific functionality,
it is wise to check whether there is an existing library module that can be used directly.
Python provides many powerful functionalities through modules distributed along with the
Python program itself, and the descriptions of all the modules can be found in the Python
documentation. To look for third-party modules with given functionalities, online search
engines are a useful resource. For example, searching for ‘Python scientific computation’ can
lead to the website of SciPy.
The Mechanism of Module Importation
The import statement creates an identifier that has the same name as the module. For
example, by using ‘import random’, ‘random.py’ is imported into the memory, and associated
with the name ‘random’ in the global binding table. To avoid name clashes and for the
convenience of reference, a module can also be given a different name when imported into
the binding table. This can be achieved by using a variant of the import statement, with the
syntax ‘import x as y’, where x is the name of the module in the file system and y is the
desired name in the binding table.
>>> import math as m
>>> m.e
2.718281828459045
>>> m. sqrt(25.0)
>>> 5.0
>>> math.e
Traceback ( most recent call last):
File "<stdin >", line 1, in <module >
NameError: name ’math ’ is not defined
In the example above, the math module is loaded into the binding table and associated
with the identifier m. As a result, by using “m.”, the corresponding binding table of the math
module can be accessed. However, the identifier “math” does not exist in the global binding
table this time.
Since both the assignment statement and the import statement changes the binding
table, they can override the value of an identifier. For example,
>>> x=1
>>> import math as x
>>> x+1 # not a number
Traceback ( most recent call last):
File"<stdin >", line 1, in <module >
TypeError: unsupported operand type(s) for +: ’module ’
and ’int ’
>>> x.pi # but a module
3.141592653589793
In the example above, x is initially bound to a number, but then rebound to a module.
The original binding is overridden. An assignment statement can also override an import
statement. For example,
>>> import math
>>> math=1
>>> math+1 # number
2
>>> math.e # error
Traceback ( most recent call last):
File "<stdin >", line 1, in <module >
AttributeError: ’int ’ object has no attribute ’e’
As shown earlier, modules such as random.py are Python programs themselves. In
fact, any Python program can be loaded as a module. To verify this, the program saving.py
can be used as an example. Suppose that another source file, textimport.py, is created under
the Desktop folder. It contains the following two lines of code

[testimport.py]
import savings
x=1
print savings.rate , "is entered as the interest rate"

testimport.py
[Savings Calculator]
Please enter the interest rate: 0.036
Please enter the number of years: 5
Please enter the initial sum of money: $10000
After 5 years , the savings will be $11934.35
0.036 is entered as the interest rate

One immediate thing to notice is that the program asks the user for the interest rate,
number of years and initial deposit again, just as if the savings.py program were executed
alone. Then it displays the message “0.036 is entered as the interest rate”. Here, savings.rate
is used to access the rate value defined in savings.py, in the same way as the use of math.e to
access the value of e defined in math.
The underlying mechanism of module importation is reflected in this example. First,
the importing module hands control over to the imported module, which is executed, with its
own binding table being the global binding table. Second, the importing module resumes
control, with the global binding table switched back to the binding table of the importing
module. A new entry added to the binding table of the importing module, associating the
name of the imported module with the binding table of the imported module. This process
can be illustrated in Fig. 3.5. The example also shows a second use of the print statement,
where a comma-separated list of expressions is put after the keyword. In this case, each
expression will be printed, with a space separating the outputs.

Duplicated Imports
If the same module is imported twice, the content of the module will not be executed by the
second import statement. For example, the following change to the testimport.py code will
not lead to any change in the runtime behavior.

[testimport.py]
x=1
import savings
import savings
print savings.rate ,"is entered as the interest rate"

The first two lines of the program remain the same as before, while the third line is
added for a second import of the same module. When this program is executed, the user will
be asked for input only once, with the same value of savings.rate being shown when the
fourth line of code is executed. Executing testimport.py from IDLE can yield the following
output.
>>> =================== RESTART==============================
[Savings Calculator]
Please enter the interest rate: 0.036
Please enter the number of years: 5
Please enter the initial sum of money: $10000
After 5 years , the savings will be $11934.35
0.036 is entered as the interest rate
>>>
It can be seen in the example above that, no operation is taken when the second
import statement is executed. Note that for the example to run as expected,savings.py must be
in a folder that is accessible by IDLE. For example, if the Desktop folder has been added to
the PYTHON_PATH environment variable as illustrated in Chap. 1, all the files in the folder
are accessible. Alternatively, if IDLE is started at the Desktop folder, all the files in the folder
are also accessible. The following example shows how this can be done on a Linux or Max
OS.

Zhangs -MacBook -Pro: anywhere$ cd


Zhangs -MacBook -Pro:~ yue_zhang$ cd Desktop/
Zhangs -MacBook -Pro: Desktop yue_zhang$ idle

The following example shows the case on a Windows OS.

c:\anywhere > cd % userprofile%


c:\Users\yue_zhang > cd Desktop/
c:\Users \yue_zhang\ Desktop > idle
Two imports of the same module behave the same as in the previous example even
when they are executed from different modules—execution of the second import statement
does not result in the module being executed again. For example, suppose that the following
two files are in the Desktop folder.

[testimport1.py]
import savings
x=1

[testimport2.py]
import savings
import testimport1
y=1
When testimport2.py is executed as the main program, the dynamic execution
sequence is:
import savings
[execute savings.py]
...
[savings.py finished]
import testimport
[execute testimport.py]
import savings
[execute savings.py]
...
[savings.py finished]
x=1
[testimport.py finished]
y=1
savings.py is executed only once, when the first line of testimport2.py is executed.
When the second line of testimport2.py is executed, testimport1.py is executed. But when the
first line of testimport1.py is executed, savings.py is not executed a second time. The same
module object is simply associated with a new entry in the binding table of testimport1. After
the execution of y = 1, the memory structure is shown in Fig. 3.6. Note that the same module
object is associated with the name savings in two different binding tables.
Reloading a module. In case the imported module is modified between the execution
of two import statements, the second import will not reflect the modification. Python has a
special function, reload, which reloads the context of an imported module by executing it
once more. For example, suppose that savings.py is changed between an import statement
and a reload function call as follows:
[savings.py initially]
print ‘[Savings Calculator]’
rate = float( raw_input("Please enter the interest rate:"))
years = int( raw_input("Please enter the number of years :"))
init = float( raw_input("Please enter the inital sum of money: $"))
final = init * (1.0+rate)**years
print "After %d years , the savings will be $%.2f" % (years , final)

[savings.py after import but before reload]


print ‘The new version ’
init=0

Execution of the import and reload operations yields the following result:
>>> import savings
[Savings Calculator]
Please enter the interest rate: 0.036
Please enter the number of years: 5
Please enter the initial sum of money: $10000
After 5 years , the savings will be $11934.35
0.036 is entered as the interest rate >>> import savings # nothing happens
>>> reload (savings)
The new version
>>> print savings. init
0
The reload function changes the context of the binding table of savings, where the
value of init becomes 0. As a result, 0 is printed by the last command in IDLE.

Branching and Looping:


Many a time, the computer needs to take different actions according to user input. For
example, when the user closes a text editor window, the operating system prompts out a
dialog box asking the user whether to save her work before quitting. According to the user
choice, the program may save the work before exiting, or exit without saving the work.
Unlike the programs in the precious chapter, the dynamic, or runtime execution sequence of
the text editor program can be different from the static lines of code written in the program.
In the example above, the code for saving the user’s work may or may not be executed at
runtime. This is called conditional execution, or branching.
Another type of dynamic behavior is looping, where the computer repeats the same
process multiple times. For example, a music player can repeatedly play the same song
multiple times. In a dynamic execution, the same piece of static code (i.e. play music) is
executed multiple times. In addition, the number of times the same code is repeated can also
depend on user input. The playing of a playlist is also typically implemented using loops, by
repeating the same music playing code on different songs.
The execution of a program can be treated as a continuous flow of statement
execution. Branching and looping can be treated as two different ways of control flow, which
refers to how a sequence of static code is put into a dynamic sequence for execution at
runtime. In contrast to branching and looping, the execution sequence introduced in the
previous chapters, where a list of statements are executed one by one, is also referred to as
the sequential control flow. In a sequential control flow, the order in which a set of statements
is executed is exactly the same as the order in which they are written. Figure 4.1 shows a
comparison between sequential, branching and looping execution sequences. This type of
diagram is called control flow diagram, or flow charts. Flow charts consist of arrows and
nodes. While arrows indicate the execution sequence, nodes can be either statements or
junctions. A junction is a binary branching node, depending on a condition, it determines
while branch to follow in dynamic execution. It turns out that a combination of the three
basic types of control low in Fig. 4.1 is sufficient to solve any computable problem—any
problem that can be solved by a computer.

CONTROLS FOR DECISION MAKING


Decision making constructs begins with a Boolean expression, an expression that returns
either True or False. Decision making structures are necessary to perform an action or a
calculation only when a condition is met.
THE ‘IF’ STATEMENT
The ‘if’ statement starts with a Boolean expression followed by a statement or a group of
statements, which is evaluated if the condition is TRUE.
If the Boolean expression evaluates to FALSE, then the next code after the end of if statement
will be executed.
Syntax :
if test expression:
Statement 1
. . Statement n
Statement
Test expression

True
Statement Block

Statement x

Eg:
x=10
if(x>0):
x=x+1
print (“The value of x:”,x)
Output:
The value of x: 11

Eg:
age=int(input(“Enter the age”))
if(age>=18):
print (“You are eligible to vote”)
Output:
Enter the age:28
You are eligible to vote

Eg:
ch=input(“Enter any character:”)
if(ch>=’A’ and ch<=’Z’):
ch=ch.lower()
print(“The entered char is in uppercase, In lower case:”,+ch)
else:
ch=ch.upper()
print(“The entered char is in lowercase, In upper case:”,+ch)
Output:
Enter any character: a
The entered char is in lowercase, In upper case:A

THE IF…ELIF..ELSE STATEMENT (ELIF/ NESTED IF)


An elif (else if) statement can be used when there is a need to check or evaluate
multiple expressions. An if…elif….else structure first checks if the ‘if statement’ is True. If it
is true, the statement in the if block gets executed.If it is false, it tests the condition in the elif
block
If the elif statement is evaluated as True, the statement in the elif block gets executed.
Otherwise, control passes to the else block.

Syntax:
if(test expression):
Statement # runs when the loop exp is True
elif testexpression:
Statements # runs when this test exp is True
else:
Statements #runs when all test exp are False

Eg:
num=int(input(“Enter any no:”))
if(num==0):
print(“The value is equal to zero”)
elif(num>0):
print(“The value is positive”)
else:
print(“The value is negative”)
Output:
Enter any no: -10
The value is negative

NESTED IF…ELIF….ELSE STATEMENTS


Conditional statements can contain another conditional statement. This structure is
found in nested if..elif..else statements. Nested conditional statements are used when ever
there is need to check for another condition after the first condition has been evaluated as
True.
Syntax:
if(test expression1):
if (test expression 1-a):
statement block 1-a
elif(test expression 1-b):
statement block 1-b
elif(test expression):
statement block 2
else:
statement block 3

Eg:
num=int(input(“Enter your age:”))
if(num>=20):
if(num>=60):
print(“seniors club”)
elif(num>=36):
print(“middle age”)
else:
print(“young adults”)
elif(num>12):
print(“youth club”)
else:
print(“too young”)
Output:
Enter your age:8
Too young

3.1.4.1 INLINE ‘IF’ STATEMENTS


An inline ‘if’ statements 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

Eg:
b=True
a=1 if b else None
Output:
1

3.1.5 LOOP STRUCTURES AND ITERATIVE STATEMENTS


A loop (or iterative statements) is a programming control structure that facilitates the
repetitive execution of a statement or a group of statements. There are two types of looping
constructs – for loop and while loop.
3.1.5.1 ‘FOR’ LOOP
The ‘for’ loop repeats a given block of code by specified number of times. It is usually
known as a determinate or definite loop because the programmer knows exactly how many
times the loop will repeat.
Syntax:
for variable in sequence:
statement block
Here ‘variable’ stores all value of each item . ‘Sequence’ may be a string, a collection or a
range which implies the loop number
A. LOOPING THROUGH AN ITERABLE
An iterable refers to anything that can be looped over, such as a string, a list of tuple
Eg:
numbers =[10,20,30,40] # for loop with a list
for i in numbers:
if(i%2==0):
print(i,“is an even number”)
else:
print(i,“is an odd number”)

Output:
10 is an even no
20 is an even no
30 is an odd no
40 is an even no
Eg:
language=(“C”,”C++”,”Java”,”Python”) # for loop with a tuple
for x in language:
print x
Output:
C C++ Java Python
Eg:
message=”PROGRAM”
for i in message:
print i
Output:
P
R
O
G
R
A
M

B. LOOPING THROUGH SEQUENCE OF NUMBERS


The built in range () function is used to iterate over ‘for’ loops.
Syntax:
range(start, end, step)

range() produces a sequence of number starting with start-(inclusive) and ending with
one less than the number end.Step argument is optional. By default, every number in the
range is incremented by 1 but we can specify a different increment using step. It can be
positive, negative but not zero.
Eg:
fornum in range(5):
print(“The numbers are:”,num)
Output:
0
1
2
3
4

Eg:
fornum in range(4,10,2):
print(“The numbers are:”,num)
Output:
468

Eg:
fornum in range(3,10):
print(“The numbers are:”,num)
Output:
3456789
Eg:
num=int(input(“Enter a no:”))
fornum in range(10+1):
print(i,”*”,num,”=”,i*num)
Output:
Enter a no:2
0*2=0
1*2=2
2*2=4
.
10*2=20

C. ‘FOR’ LOOP WITH ‘ELSE’


Python supports to have ‘else’ statement with a loop statement. If the ‘else’ statement
is added with a ‘for’ statement, it gets executed when the loop has finished iterating the list. A
break statement terminates ‘for’ loop iteration.
Example:
nos=[10,20,30,40,50,60]
num=int(input(“enter an item to be searched:”))
for i in range(len(nos)):
if(nos[i]==num)):
print(“The searched item is found at position”,i)
else:
print(“The item is not in the list”)

EXPLANATION:
“for i in nos”
Here i denotes each item in the list called nos. This is used when we need to interrupt each
item

“for i in range(len(nos))”
This is used when we need to interrupt the position of each item. This ‘for’ loop can also be
used in the following ways:
for i in range(6)
(or)
for i in range(0,6)
Output1:
Enter an item to be searched: 10
The searched item is found at position 0
Output2:
Enter an item to be searched: 100
The item is not in the list
3.1.5.2 ‘WHILE’ LOOP
The while loop provides a mechanism to repeat one or more statements while a
particular condition is true.
The condition is tested before any of the statements in the statement block is
executed.
If the condition is true, only then the statements will be executed otherwise if the
condition is false, the control will jump to the statement immediately outside the while loop
block.
syntax:
while(condition):
statement block
statement y

EXAMPLE1: AMSTRONG NUMBER


n= int(input(“Enter a Number:”))
s=0
num=n
while(n>0):
r=int(n%10)
b=int(s+(r**s))
n=int(n/10)
if(s==num):
print(“The number is an armstrong number”)
else: print(“The number is not an armstrong number”)
Output1:
Enter a number: 153
The number is an armstrong number

Output2:
Enter a number: 128
The number is not an armstrong number

EXAMPLE2: SUM OF ‘N’ NATURAL NUMBERS


n=int(input(“Enter the limit:”))
s=0
i=1
while(i<+n):
s=s+i
i=i+1
print(“Sum of first n natural nos:”,s)

Output:
Enter the limit:5
Sum of first n natural nos:15

‘WHILE’ LOOP WITH ‘ELSE’


If the else statement is used with a while loop, it is executed when the condition
becomes false. While loop can be terminated with a break statement. In such a case, the else
part gets ignored. Hence, a while loop’s else part runs when no break occurs and the
condition is false.
Example:
count=0
while(count<5):
print(count,”is less than 5”)
count=count+1
else:
print(count,”is not less than 5”)

Output:
0 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

NESTED LOOPS
Nesting is placing 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.
Syntax for nested for loop:
for variable in sequence:
for variable in sequence:
statement(s)
statement(s)
Syntax for nested while loop:
while test_expression:
while test_expression:
statement(s)
statement(s)
Example for nested for loop:
Printing ‘n’ prime numbers
num=int(input(“Enter the limit:”))
for a in range(1,num):
k=int(a**0.5)
for b in range(2,k+1):
if(a%b==0):
break
else:
print(a)

Output:
Enter the limit:12
1 2 3 5 7 11
Example for nested while:
num=int(input(“Enter the limit:”))
a=1
while(a<=num):
k=int(a**0.5)
b=2
while(b<=k):
if(a%b==0):
break
b=b+1
else:
print(a)
a=a+1
Output:
Enter the limit:12
1 2 3 5 7 11

CONTROL STATEMENTS:
Control statements change the execution from normal sequence. Loops iterate over a
block of code until test expression is false, but sometimes when we wish to terminate the
current iteration or even the whole loop without checking the test expression, the control
statements serves the purpose. There are three control statements:
1) break
2) continue
3) pass
1) BREAK STATEMENT
break statement is used to end the current loop and transfer the control to the
statements immediately following the loop.
If it is inside a nested loop, break will terminate the innermost loop.
Syntax:
while (condition):
....
break
....
(or)
for variable in range :
....
break ..
Example: Example:
i=1 i=1
while(i<=10): while(i<=10):
print(“i=”,i) if(i==5):
if(i==5): break
break print(“i=”,i)
i=i+1 i=i+1
print(“Done”) print(“Done”)
Output: Output:
i=1 i=1
i=2 i=2
i=3 i=3
i=4 i=4
i=5 Done
Done

The following figures illustrate the transfer of control using break statement:
while ….. for ….. for …..
….. ….. …..
if condition: if condition: for…..
break break ….
….. ….. if condition:
…… …… break
……
Transfer control out of the Transfer control out of the …….
‘while’ loop ‘for’ loop ……
Transfer control out of the
inner ‘for’ loop

Example:
for i in ‘python’:
if(i==’h’):
break
print(“the current letter is: “,i)

Output
The current letter is: p
The current letter is: y
The current letter is: t
Flowchart:
II) THE ‘CONTINUE’ STATEMENT:
The continue statement skips remaining statement(s) in the present
iteration and directs the program to the next iteration. “If” rejects all the remaining statements
in the current iteration of the loop and moves the control back to the top(begining) of the
loop. It can be used with both “for” and “while” loop.

Syntax:
continue

Example

1) for i in range(1,11):
if(i==5):
continue
print(i)
print(“Done”)

Output:
1 2 3 4 6 7 8 9 10 Done

2)num=0
while(num<10):
if(num==5):
continue
print(num)
num=num+1
print(“Done”)

Output:
01234

3) for i in ‘python’:
if(i==’h’):
continue
print(“Current Letter:”,i)
Output:
Current Letter:p
Current Letter:y
Current Letter:t
Current Letter:o
Current Letter:n

While… for… For….


….. ….. ……
If condition: If condition: for…
Continue Continue …..
….. ….. If condition:
……. ……. Continue
Therefore control to the condition Therefore control to the …..
of the “while” loop condition of the “for” loop .…..
…….
Therefore control to the
condition of the “for” loop

III) THE ‘PASS’ STATEMENT:


Pass is a null operation. The interpreter reads and executes the pass statement but
returns nothing. A pass statement is commonly used as a place holder whenever python’s
syntax requires a line that we can’t provide at the moment. It is used to mark codes that will
be eventually be written.

Syntax:
Pass

Example:

For letter in “hello”:


pass
print(“Pass:”,letter)
print(“Done”)

Output:

Pass: h
Pass: e
Pass: l
Pass: l
Pass: o
Done

3.1.3 INFINITE LOOP:


A loop becomes infinite loop when a test condition never becomes false(i.e
condition is always true)
Example:

While true:
n=int(input(“Enter an integer:”))
print(“The double of “,n,”is”,2*n)

Output:
Enter an integer:2
The double of 2 is 4
Enter an integer:4
The double of 4 is 8
Enter an integer:

3.1.3.1 LOOP WITH CONDITION AT THE TOP:


A while loop with a condition placed at the top is a standard while loop with no break
statement. The loop ends when the condition becomes false.

Example:

num=10
s=0
i=1
while(i<=num):
s=s+i
i=i+1
print(“The sum is:”,S)

Output:

The sum is 55

3.1.3.2 LOOP WITH CONDITION AT THE MIDDLE:


This loop is usually implemented with an infinite loop and a conditional break in
between the loop’s body.
Example:
# to detect a vowel
vowels=”AEIOUaeiou”
while True:
a=input(“Enter a vowel:”)
if(a in vowels):
break
print(“Not a vowel. Try again”)
print(“Finally entered a vowel”)
Output:

Enter a vowel: x
Not a vowel. Try again
Enter a vowel: a
Finally entered a vowel

3.1.3.3 LOOP WITH CONDITION AT THE BOTTOM:


This kind of loop ensures that the body of the loop is executed at least once. It can
be implemented with an infinite loop along with a conditional break at the end.

Example:

num1,num2=10,20
print(“MENU”)
print(“1. Add”)
print(“2. Sub”)
print(“3. Mul”)
print(“4. Div”)
print(“5. Exit”)
choice=int(input(“Enter Choice:”))
while(choice!=5)
if(choice==1):
print(“Sum”,(num1+num2))
if(choice==2):
print(“Diff”,(num1-num2))
if(choice==3):
print(“Mul”,(num1*num2))
if(choice==4):
print(“Div”,(num1/num2))
if(choice==5):
print(“Exit”)
break
print(“End”)
Output
MENU
1. Add
2. Sub
3. Mul
4. Div
5. Exit
Enter Choice: 1
Sum 30
End
3.1.4 FRUITFUL FUNCTIONS
A fruitful function is a function that returns a value when it is called most of the built-
in functions are fruitful. The following is an example where we define fruitful function.

Example: To add two numbers

def add(x,y): // FORMAL PARAMETERS


sum=x+y
return sum
a=int(input(“Enter A=”))
b=int(input(“Enter B=”))
print(“The sum=”,add(a,b)) // ACTUAL PARAMETERS

Output:

Enter A=2
Enter B=3
The sum=5

As soon as a return statement executes, the function terminates without


executing any subsequent statements. Code that appears after a return statement is called
dead code.

3.1.5 FUNCTION PARAMETERS

Functions are classified based on whether the arguments are present or not and
whether a value is returned or not.
 Function with no arguments and no return value.
 Function with arguments and no return value.
 Function with arguments and with return value.
 Function with no arguments and with return value.
3.1.5.1 Function With No Arguments And No Return Values:
In this prototype, no data transfer take place between the calling
function and the called function i.e) the called function does not receive any data from the
calling function and does not send back any value to the calling function.

Example:
def add():
a=10;b=20
c=a+b
print(“Sum:”,c)
def sub():
a=20;b=10
c=a-b
print(“Sub:”,c)
def mul():
a=10;b=20
c=a*b
print(“Mul:”,c)
def div():
a=20;b=10
c=a/b
print(“Div:”,c)
add()
sub()
mul()
div()
Output:

Sum:30
Sub:10
Mul:200
Div:2.0

3.1.5.2 FUNCTION WITH ARGUMENTS AND NO RETURN VALUES:


In this prototype, data is transferred from the calling function to the called
function i.e) the called program receives some data from the calling function and does not
send back any value to the calling function.
Example:
def add(x,y):
z=x+y
print(“Addition of a+b:”,z)
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
add(a,b)
Output:
Enter A:20
Enter B:30
Addition of a+b: 50

3.1.5.3 FUNCTION WITH ARGUMENTS AND WITH RETURN VALUES:


Here, the data is transferred between the calling function and the called function.
Example:
def mul(x,y):
return(x*y)
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
c=mul(a,b)
print(“Multiplication of a*b:”,c)
Output:
Enter A:2
Enter B:3
Multiplication of a*b:6
3.1.5.4 FUNCTION WITH NO ARGUMENTS AND WITH RETURN VALUES:
Here, the calling function does not pass any arguments to the called
function, but the called function returns some value.
Example:
def mul():
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
c=int(input(“Enter C:”))
result=(a*b*c)
return(result)
d=mul()
print(“Multiplication of a*b*c:”,d)
Output:
Enter A:2
Enter B:3
Enter C:4
Multiplication of a*b*c:24
3.1.6 RECURSIVE FUNCTION:

A Recursive function is defined as a function which calls itself one or more times in its body.
Example:
def fact(number):
if(number==0 or number==1):
return 1
else:
return (number* fact(number-1))
no=int(input(“Enter the number:”))
print(“The Factorial value of ”,no,”is:”,fact(no))
Output:
Enter the number :5
The Factorial value of 5 is 120
3.1.6.1 FUNCTION WITH MORE THAN ONE RETURN VALUE:
Python allows to return more than one value at a time.It is an alternative of writing
separate functions for returning individual values.
Example:
def calc(no1,no2):
add=no1+no2
sub=no1-no2
mul=no1*no2
div=no1/no2
return add,sub,mul,div
num1=int(input(“Enter the 1st number:”))
num2=int(input(“Enter the 2nd number:”))
a,s,m,d=calc(num1,num2)
print(“Addition:”,a)
print(“Subtraction:”,s)
print(“Multiplication:”,m)
print(“Division:”,d)
Output:
Enter the 1st number: 9
Enter the 2nd number: 6
Addition: 15
Subtraction: 3
Multiplication: 54
Division: 1.5

STRINGS
Strings are defined as a contiguous set of Unicode characters which may consists of
letters,numbers,special symbols or a combination of these types represented within the
quotation mark.It is an immutable data type.
A string can be enclosed in single(‘),double(“) and tuple(‘’’ or “””) quote.
Initialization
String can be initialized by using an assignment statement.
Syntax:
var_name=’String’
var_name=”String”
var_name=”””String””” or ‘’’String’’’
3.1.8.1 ACCESSING STRING VALUE
A String can be accessed by using the square brackets or index operator [].The initial
character or substring takes zero as its index and the set are numbered sequentially.
Syntax:
string_variable[index_number]
Example:
a=”hello”
a[0]= h
a[4]=o
a[-2]=l
String Slicing
The slicing [:] operator is used to access a range of characters in a string and create
substring.
Syntax:
string_variable[start:finish-1]
Example:
a=”Python Programming”
a[5:11] output: ‘n Prog’
a[5: ] output: ‘n Programming’
a[-18:-12] output: ‘Python’
a[-18:-13] output :’Pytho’
3.1.8.2 STRING CONCATENATION
Combining multiple string to form a single string is called as String Concatenation.
The (+) operator is used for this.
Syntax:
“Stirng_var1” + “String_var2” +.....+String_var n”
Example 1:
“have”+ “a” +” nice” + “day”
Output:
have a nice day
Example 2:
a=”Python”
b=”Programming”
print(“a+b=”,a+b)
print(a+b)
Output:
a+b= Python Programming
Python Programming
3.1.8.3 APPEND A STIRNG USING ‘+=’ OPERATOR
Example
str=”Hello,”
name=input(“Enter your name:”)
str+=name
str+=”.”Welcome to Python Programming”
Output
Enter your name: Raja
Hello,Raja.Welcome to Python Programming.

REPEAT A STRING USING ‘*’ OPERATOR


str=”Hello”
print(str*3)
Output
HelloHelloHello
3.1.8.4 THE ‘STR()’ FUNCTION
It is used to convert values of any other type into string type.
Example
str1=”Hello”
var=7
str2=str1+str(var)
print(str2)
Output
Hello7
Example for end keyword
print(“Hello”,end=’ ‘)
print(“World”)
Output
HelloWorld
Specifying ‘step’ while slicing strings
In the slice operation,we can specify a third argument as the step,which refers to the
number of characters to move forward after the first characters is retrived from the string.The
default value of step is 1.
Example:
str=” Welcome to the Python class”
print(str[2:10]) # default step=1 Output: “lcome to”
print(str[2:10:1) # Step=1,Same as default Output: “lcome to”
print(str[2:10:2]) # Skips 2nd char loet
Note: White space characters are also counted,as they are part of the string.
3.1.8.5 STRING FORMATTING OPERATOR
The % operator takes a format string on the left( i.e. %d %s etc) and the
corresponding values in a tuple on the right.
Syntax:
“format specifier” % (values)
Example:
name=”Raja”
age=10
print(“Name=%s and Age=%d” %(name,age))
print(“Name=%s and Age=%d” %(“Balaji”,11))
Output:
Name=Raja and Age=10
Name=Balaji and Age=11
The ‘strip()’ functions
The strip() function will strip(from both ends) any combination of the specified
characters in the string.
Example:
str=”abcdefghijkl”
print(str.strip(‘abc’))
Output:
“defghijkl”
Slice Opeartion with last argument alone
str=”Welcome to the world of python programming”
print(“str[: : 3]=”,str[: : 3]) #Entire string is used in steps
print(“str[: : -3]=”,str[: : -3])
print(“str[: : -1]=”,str[: : -1])
Output:
str[: : 3]=wceohwloph oai
str[: : -3]=gmrrnt r ttml
str[: : -1]=gnimmargorp nohtyp fo dlrow eht ot emoclew
3.1.8.6 STRINGS ARE IMMUTABLE
Python strings are immutable which means that once created they can't be changed.
Whenever we try to modify an existing string variable, a new string is created.

Eg: greet = "Hello, World" greet = "Hello World"


greet [0] ='M' new_greet = 'M' + greet [1 :]
print (greet) print (new_great)
Op: Error Op: Mello, World.

The ord () and chr() functions


Ord() - returns the ASCII code of the character
chr() - returns character represented by a ASCII number.
Eg: Eg: Eg: Eg:
ch = ‘R’ print (chr (82)) print (chr (112)) print (ord (ch))
print (ord (ch))
Op:82 Op:R Op:p Op:112

The 'in' and 'not in’ Operators


Eg: str1 = "welcome to world of python" Eg: str1=” Welcome to python"
str2 = "world" str2 = "hello"
if str2 in str1: if str2 not in str1:
print(" Found") print(" True")
else: else:
print(“Not Found”) print(“False”)

Op: Found
Eg: Eg: Eg:
'u' in "stars" 'v' not in" stars" "vi" in victory
False True True

3.1.8.7 ITERATING STRING


Iterating using ‘for’ loop Iterating using ‘while’ loop
Eg: str = “Welcome to python” msg = “welcome to python”
for i in str : index = 0
print(i, end = “ ’’ ) while (index < len(msg)):
letter = msg [index]
Op: Welcome to python print(letter, end =' ’)
index + 1
Op: welcome to python

3.1.8.8 STRINGS FUNCTIONS AND METHODS


There are many built-in - string methods which are available through the class string.
i) Length of the string_ len( )
Determines the size of the string ie number Characters.
Syntax :
len (string_ variable)
Eg: str = “ Programming" Op:11
print(len (str))
The last character can be accessed by subtracting 1 from the output of the len()
function.
ii) Capitalize ( )
Capitalizes the first character in a string
Syntax:
string_var. capitalize()
Eg: str = "programming "
print (str. capitalize ( ))
Op: Programming

iii) Upper( )
All the characters in a string will be converted to uppercase
Syntax:
string_var.upper()
Eg: str = "python' Op: PYTHON
print ( str. upper())
iv) Lower( )
All the characters in a string will be converted to lowercase
Syntax:
string_var.lower()
Eg: str = "PYTHON” Op: python
print ( str.lower())

v) Count ( )
This method will return the total number of occurrences f the given substring within the given
range.
Syntax:
str.count ( Sub [, start[, end ]])
The start & end are optional arguments.
Eg: str1= “ String string String string String"
print (str1. count (“String" "))
print (str1. count ("string”))
Op:
3
2
vi) Index( )
The lowest index in the given string will be returned, where the substring is found
Syntax :
str.index (sub[, start[, end]])

The start & end are optional arguments.


Eg : str1 = "String string String string String”
print (str1.index("String ", 3))
Op:14
vii) Ends with
This method will return true, if all the strings end with the suffix specified & will return a
false if not . A tuple of suffixes can also be given as a suffix.
Syntax:
str.endswith ( suffix [,start[, end]])
The start & end are optional arguments.
Eg: str1 = “String string String string string”
print( str1.endswith( “String” ))
print ( str1.endswith ("string", 0, 27))
Op: True
False
vii) Find ()
This method will return the lowest index of the given string, where the substring is found
such that the substring is present in the slice s[start: end].
Syntax:
str. find ( sub [, Start[, end]] )
The start & end are optional arguments. -1 will be returned in cases where the
substring cannot be found.
Eg: a = "String string String string String"
print (a. find ("string"))
Op: 7
ix) Title( )
This method will return title case version of the given string(first letter of the word in
uppercase & the rest in lower case)

Syntax :
str. title( )
Eg :
str1 = "string string string string"
print (str1.title ())
Op: String String String String

x) Split()
This method splits the string according to the delimiter (space, if not provided) & returns list
of substrings; split into almost ‘num’ substrings if given.
Syntax:
str.split (“Delimiter”, num)

Eg: Op:
strl = "madhuri aritha abi Sheeba"
str2 = “madhuri *anitha * abi* sheeba"
print (strl.split ( )) [ 'madhuri', 'anitha' 'abi', 'sheeba']
purt (str1. split ("")) ['madhuri, 'aritha' 'abe' 'Sheeba']
print (str2.Split ('*')) ['madhuri',' anitha', 'abi'', 'Sheeba']
print (str2.split ('*',2)) ['madhuri', 'anitha' 'abi * sheeba']
print (str2. split ('*', 3)) ['madhuri', 'anitha', 'abi', 'sheeba']

3.1.8.9 BOOLEAN METHODS


The string methods that will evaluate to a Boolean value ie True or False.
i) str. isalnum( )
This method returns true if the string consists of only alphanumeric characters.
Eg: str1 = "String string String string String3"
str2 = "StringstringStringstringStrings3”
print (str1. isalnum( ))
print (str2. isalnum ( ))
Op: False
True
ii) str. isalpha( )
This method returns true if all the string consists of only alphabetic character.
Eg: str1 = "StingstringStringstringString 3"
str2 = "StringstringStringstringString”
print (str1. isalpha())
print(str2.isalpha())

Op: False
True
iii) str.islower ( )
This method returns true if all the characters in the string are in lower case.
Eg: str1 = "how Are you"
print (str1.islower( ))
Op: False

iv) str.isspace( )
This method will returns true if the given string contains only whitespace characters & false
otherwise.
Eg: str1= “ “
print (str1. isspace( ))
Op: True
v) str.istitle ( )
This method will returns true if the given string is a title cased string & it should have at least
one character.
Eg: str1 ="" String String string String”
str2 - " How Are You"
print (str1.istitle ( ) )
print (str2. istitle ( ))
Op: False
. True

vi) str.isnumeric()
Returns true if all the characters in the string are numeric characters.
Eg: str1 = '123 how 456' Op: True
str2 = '123456'
print (str1.isnumeric( ))
print (str2.isnumeric( ))

vii) str.isupper( )
This method returns true it all the characters in the string are in uppercase.
Eg: str1="string String string"
print (str1.isupper( ))
Op: False

3.1.8.10 COMPARING STRINGS


We can compare strings using relational operators. It is done by using the ASCII value of the
characters.
ASCII value of A-Z is 65-90
ASCII value of a-z is 97 -122

Operator Description Example

== Returns true if two strings are >>> “Abc" = = "Abc"


equal >>>True

!= or <> Returns true, if two strings are >>> “Abc" ! = "Abc"


not equal >>>True

> Returns true,if the first string >>> “abc" > "Abc"
is greater than the second >>>True
string

< Returns true,if the second >>> “abc" < "abc"


string is greater than the first >>>True
string

>= Returns true,if the first string >>> “aBC" >= "ABC"
is greater than or equal to the >>>True
second string

<= Returns true,if the second >>> “ABC" <= "ABC"


string is greater than or equal >>>True
to the first string

EXAMPLE PROGRAM :

1.SQUARE ROOT OF A NUMBER:


while True:
print(“Enter ‘x’ to exit :”)
num=input(“Enter a number:”)
if(num==’x’):
break
else:
number = float(num)
number_sqrt=number**0.5
print(“square root of %0.2f is %0.2f”%(number, number_sqrt)
Output:
Enter ‘x’ to exit
Enter a number: 3
square root of 3.00 is 1.73
Enter ‘x’ to exit
Enter a number:x
2.GCD OF TWO NUMBERS
num1=int(input(“enter first number:”))
num2=int(input(“enter second number:”))
for i in range(1,min(num1,num2)+1):
if(num1%i==0 and num2%i==0):
gcd=i
print(“GCD of “,num1,”and”,num2”is”,gcd)
Output:
enter first number: 6
enter second number: 2
GCD of 6 and 2 is 2
3.EXPONENTIATION OF A NUMBER
n=input(“Enter a number:”)
n=int(n)
e=input(“Enter an exponent:”)
e=int(e)
r=n
for i in range(1,e):
r=n*r
print(r)

Output:
Enter a number: 3
Enter an exponent: 2
9

4.SUM AN ARRAY OF NUMBERS


def listsum(numlist):
if len(numlist)==1:
return numlist[0]
else:
return numlist[0] + listsum(numlist[1:])
print(“Sum:”,listsum([1,3,5,7,9]))
Output:
Sum:25
5.FIBONACCI SERIES
n=int (input(“Enter a number:”))
a,b=0,1
c=a+b
print(“FIBONACCI SERIES”)
print(a)
print(b)
for i in range(3,n+1):
print(c)
a=b
b=c
c=a+b
Output:
Enter a number: 5
FIBONACCI SERIES
0
1
1
2
3
6.SEARCH AN ELEMENT IN AN ARRAY USING BINARY SEARCH
def binary_search(item_list,search_item):
first=0
last=len(item_list)-1
middle=(first<=last)//2
while(first<=last):
if(item_list[middle]<search_item):
first=middle+1
elif(item_list[middle]==search_item):
print(“Found”)
break
else:
last=middle-1
middle=(first+last)//2
if(first>last):
print(“Not found!”)
binary_search([1,2,3,5,8],3)
binary_search([1,2,3,5,8],9)
Output:
Found
Not Found!

7.COUNT THE NUMBER OF VOWELS


s=input(“Enter the string:”)
count=0
for i in s:
if(i in ‘aeiouAEIOU’):
count+=1
print(“number of vowels :”,count)
Output:
Enter the string: Hello
number of vowels: 2

8. SEARCH AN ELEMENT IN AN ARRAY USING LINEAR SEARCH


list=[4,1,2,3,6]
search=int(input(“Enter the element to be searched:”))
for i in range(0,len(list)):
if(search==list[i]):
print(“Element found”)
print(“Element not found”)
Output:
Enter the element to be searched: 2
Element found
Enter the element to be searched: 9
Element not found

Lists
 A list is a sequence of values. The values in a list are called elements or sometimes items.
 It can be written as a list of comma-separated values between square brackets[ ].
 Items in the lists can be of different data types.

LIST OPERATIONS
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison

Operations Examples Description


>>>a=[2,3,4,5,6,7,8,9,10] list of nine integers
>>>b=['crunchy frog', 'ram bladder'] list of two strings
Creation
>>>c=['spam', 2.0, 5, [10, 20]] list of a string, a float, an integer, and
# A list within another list is nested another list.
Accessing the item in position 0
Accessing the item in position 8
Indexing >>>print(a[0]) # 2 Accessing a last element using
>>>print(a[8]) # 10 negative indexing.
(Accessing >>>print(a[-1]) # 10
elements on # The expression inside the brackets specifies
a List using the index. The indices start at 0.
[] operator)
>>>print(a[0:3]) # [2, 3, 4]
Printing a part of the list.
Slicing >>>print(a[0:]) # [2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>b=[20,30]
Adding and printing the
>>> print(a+b) #[2, 3, 4, 5, 6, 7, 8, 9, 10, 20,
Concatenation items of two lists.
30]
Repetition >>>print(b*3) # [20, 30, 20, 30, 20, 30] Repeats a list a given number of times
>>>print(a[2]) # 4
Updating >>>a[2]=100 Updating the list using index value.
>>>print(a) # [2, 3, 100, 5, 6, 7, 8, 9, 10]
>>>print('apple' in a) # True
Returns True if element is present
Membership >>>print(100 in a) # False
in list. Otherwise returns false.
>>>print(2 not in a) # False
>>>b=[2,3,4] Returns True if all elements in
Comparison >>>print(a==b) # False both elements are same. Other-
>>> print(a!=b) # True wise returns false
LIST SLICES
List slicing is an operation that extracts a subset of elements from a list and
packages them as another list.

Syntax
Listname[start:stop] # default start value is 0
Listname[start:stop:steps] # default stop value is n-1

Example
Slices Description
a=[9,8,7,6,5,4]
a[0:3] >>>print(a[0:3]) # [9, 8, 7] Printing a part of a list from 0 to 2.
a[:4] >>>print(a[:4]) # [9, 8, 7, 6] Default start value is 0. So prints from 0 to 3
Default stop value will be n-1. So prints from 1 to
a[1:] >>>print(a[1:])#[8, 7, 6, 5, 4]
5
a[:] >>>print(a[:])#[9, 8, 7, 6, 5, 4] Prints the entire list
a[2:2] >>>print(a[2:2]) # [ ] Print an empty slice
a[0:6:2] >>>print(a[0:6:2]) # [9, 7, 5] Slicing list values with step size 2
>>>print(a[::-1]) # [4, 5, 6, 7,
a[::-1] Returns reverse of given list values
8, 9]

A slice operator on the left side of an assignment can update multiple elements.
Example
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t # ['a', 'x', 'y', 'd', 'e', 'f']

LIST METHODS
 Methods used in lists are used to manipulate the data quickly.
 These methods work only on lists.
 They do not work on the other sequence types that are not mutable, that is, the
values they contain cannot be changed, added, or deleted.

Syntax
list name.method name( element/index/list)

Method Syntax Example Description


>>> a=[1,2,3,4,5]
Adds a new element to the end
a.append(element) >>> a.append(6)
of a list
>>> print(a) # [1, 2, 3, 4, 5, 6]
>>> a.insert(0,0) Insert an item at the defined
a.insert(index,element)
>>> print(a) # [0, 1, 2, 3, 4, 5, 6] index
>>> b=[7,8,9]
Takes a list as an argument and
a.extend(b) >>> a.extend(b)
appends all of the elements
>>> print(a) # [0, 1, 2, 3, 4, 5, 6, 7, 8,9]
Returns the index of
a.index(element) >>> a.index(8) # 8
the first matched item
>>> a.sort() Arranges the elements of the
a.sort()
>>> print(a) # [0, 1, 2, 3, 4, 5, 6, 7, 8] list from low to high
>>> a.reverse() Reverse the order of items in
a.reverse()
>>> print(a) # [8, 7, 6, 5, 4, 3, 2, 1, 0] the list
a.pop() >>> print(a.pop()) #0 Removes and returns an ele-
Method Syntax Example Description
# Deleting Element ment at the last
a.pop(index) Removes the particular ele-
>>> print(a.pop(0)) #8
# Deleting Element ment and return it
a.remove(element) >>> a.remove(1)
Removes an item from the list
# Deleting Element >>> print(a) # [7, 6, 5, 4, 3,2]
Returns the count of number
a.count(element) >>> print(a.count(6)) # 1 of items passed as an argu-
ment
>>> b=a.copy() Returns a shallow copy of the
a.copy()
>>> print(b) # [7, 6, 5, 4, 3, 2] list
return the length of the
len(list) >>> print(len(a)) #6
length
return the minimum element
min(list) >>> print(min(a)) #2
in a list
return the maximum element
max(list) >>> print(max(a)) #7
in a list.
>>> a.clear() Removes all items from the
a.clear()
>>> print(a) #[] list.
>>> del(a)
del(a) >>> print(a) # Error: name 'a' is not delete the entire list.
defined

LIST LOOP/ TRAVERSING A LIST


In Python lists are considered a type of iterable. An iterable is a data type that can return
its elements separately, i.e., one at a time.
1. For loop
2. While loop
3. Infinite loop

1. List using For Loop


The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
Iterating over a sequence is called traversal.
Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code using indentation.

Syntax
for <item> in <iterable>:
<body>
Example 1: Accessing Element
a=[10,20,30,40,50]
for i in a: O/P 1 O/P 2 O/P 3
print(i) 10 0 10
Example 2: Accessing Index 20 1 20
a=[10,20,30,40,50] 30 2 30
for i in range(0,len(a)): 40 3 40
print(i) 50 4 50
Example 3: Accessing Element using Range
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(a[i])
2. List using While loop
 The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
 When the condition is tested and the result is false, the loop body will be skipped
and the first statement after the while loop will be executed.
Syntax:
while (condition):
body of while
Example: Sum of elements in list
a=[1,2,3,4,5]
i=0 sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum) # 15

3. Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example
a=1
while (a==1):
n=int(input("enter the number"))
print("you entered:" , n)
Output
Enter the number 10
you entered:10
Enter the number 12
you entered:12

LIST MUTABILITY
 Lists are mutable which means that value of its elements can be changed.
 Using the indexing operator (square brackets[ ]) on the left side of an assignment, one
of the list items can be updated.

Example Description

>>> a=[1,2,3,4,5] changing single element


>>> a[0]=100
>>> print(a) # [100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a) # [100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) # [4, 5] them.
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the de-
>>> print(a) # [20,30,45,1, 2, 3, 4, 5] sired location.

State Diagram
Lists are represented by boxes with the word “list” outside and the elements of the list in-
side.
Example
cheeses = ['Cheddar', 'Edam', 'Gouda']
numbers = [17, 123]
empty = [] # A list that contains no elements is called an
empty list; you can create one with empty brackets, [].

List Mapping
You can think of a list as a relationship between in-
dices and elements. This relationship is called a mapping; each index “maps to” one of the ele-
ments. (shown in the above figure)

ALIASING (COPYING)
 Creating a copy of a list is called aliasing. When you create a copy both list will be
having same memory location. Changes in one list will affect another list.
 Aliasing refers to having different names for same list values.
Example Output
a= [1, 2, 3 ,4 ,5]
b=a
print(b) [1, 2, 3, 4, 5]
print(a is b) True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]

 The association of a variable with an object is called a reference. In this example, there are
two references to the same object.
 An object with more than one reference has more than one name, so we say that the object is
aliased.
 A single list object is created and modified using the subscript operator.
 When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced.
 This type of change is what is known as a side effect. This happens because after
the assignment b=a, the variables a and b refer to the exact same list object.
 The variables a and b are aliases for the same object. This phenomenon is known
as aliasing.
CLONING LISTS
 To prevent aliasing, a new object can be created and the contents of the original can
be copied which is called cloning.
 Creating a copy of a same list of elements with two different memory locations is
called cloning.
 Changes in one list will not affect locations of another list.
 Cloning is a process of making a copy of the list without modifying the original list.

Example 1: Cloning using Slicing


>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b) # [1,2,3,4,5]
>>>print(a is b) # False
Example 2: Cloning using list( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b) # [1,2,3,4,5]
>>>print(a is b) # false
Example 3: Cloning using copy() method
>>>a=[1,2,3,4,5]
>>>b=a.copy()
>>>print(b) # [1, 2, 3, 4, 5]
>>>print(a is b) # False
LIST PARAMETERS
 In python, arguments are passed by reference.
 If any changes are done in the parameter which refers within the function, then
the changes also reflects back in the calling function.
 Passing a list as an argument actually passes a reference to the list, not a copy of
the list.
 Since lists are mutable, changes made to the elements referenced by the parame-
ter change the same list that the argument is referencing.
Example 1
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a) # [2,3,4,5]
Example 2
def insert(a):
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a) # [30, 1, 2, 3, 4, 5]

TUPLES
 A tuple is a sequence of values.
 The values can be any type, and they are indexed by integers.
 Tuples are immutable. i.e. once a tuple has been created, you can't add elements to a
tuple or remove elements from the tuple.
 A tuple is same as list, except that the set of elements is enclosed in parentheses instead
of square brackets.
 Syntactically, a tuple is a comma-separated list of values:
o >>> t = 'a', 'b', 'c', 'd', 'e'
 Tuple can be converted into list and list can be converted in to tuple.

Methods Example Description


>>> a=(1,2,3,4,5)
It converts the given tuple
list( ) >>> a=list(a)
into list.
>>> print(a) # [1, 2, 3, 4, 5]
>>> a=[1,2,3,4,5]
It converts the given list into
tuple( ) >>> a=tuple(a)
tuple.
>>> print(a) # (1, 2, 3, 4, 5)

Benefits of Tuple
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.

Operations on Tuples
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison

Operations Examples Description


Creating the tuple with elements of
Creating a tuple >>>a=(20,40,60, 'apple', 'ball')
different data types.
>>>print(a[0]) # 20 Accessing the item in position 0
Indexing
>>>print(a[3]) # apple Accessing the item in position 2
Slicing >>>print(a[2:4]) # (60,'apple') Displaying items from 1st till 2nd
>>> b=(2,4)
Adding tuple elements at the end of
Concatenation >>>print(a+b)
another tuple elements
# (20,40,60, 'apple', 'ball',2,4)
Repetition >>>print(b*2) # (2,4,2,4) Repeating the tuple in n no. of times
>>>print('apple' in a) # True
Returns True if element is present in tu-
Membership >>>print(100 in a) # False
ple. Otherwise returns false.
>>>print(2 not in a) # False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements in both ele-
Comparison
>>>print(a==b) # False ments are same. Otherwise returns false
>>>print(a!=b) # True

Tuple Methods
Methods Example Description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the first
>>> print(a.index(5)) # 4 matched item.
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the given
>>>print(a.count(3)) #1 element.
len(tuple) >>>print(len(a)) # 5 Return the length of the tuple
min(tuple) >>>print(min(a)) # 1 Return the minimum element
in a tuple
max(tuple) >>>print(max(a)) # 5 Return the maximum element
in a tuple
del(tuple) >>>del(a) Delete the entire tuple.
Tuple assignment
 The left side is a tuple of variables; the right side is a tuple of expressions. Each value is as-
signed to its respective variable. All the expressions on the right side are evaluated before any
of the assignments.
 The number of variables on the left and the number of values on the right have to be the same:

Uses of Tuple assignment


 To split an email address into a user name and a domain.
Example
addr = 'monty@python.org'
uname, domain = addr.split('@')
print(uname) # monty
print(domain) # python.org
 It is often useful to swap the values of two variables.
Example
Swapping using temporary variable Swapping using tuple assignment
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)

Multiple assignments
 Multiple values can be assigned to multiple variables using tuple assignment.
Example
>>>(a,b,c)=(1,2,3)
>>>print(a) #1
>>>print(b) #2
>>>print(c) #3
Tuple as return values
A function can only return one value, but a tuple can return multiple values.
Example 1: To find Quotient and Remainder
If you want to divide two integers and compute the quotient and remainder, it is inefficient
to compute x/y and then x%y. It is better to compute them both at the same time.
The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder.
>>> quot, rem = divmod(7, 3)
>>> print(quot) #2
>>> print(rem) #1
Example 2: To find Minimum and Maximum Number
max and min are built-in functions that find the largest and smallest elements of a se-
quence. min_max computes both and returns a tuple of two values.
def min_max(t): return min(t), max(t)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small) #1
print("biggest:",big) #6

VARIABLE-LENGTH ARGUMENT TUPLES


Functions can take a variable number of arguments.
Gathers
A parameter name that begins with * gathers arguments into a tuple. The gather parame-
ter can have any name you like, but args is conventional.
Example: printall takes any number of arguments and prints them
def printall(*args): print(args)
printall(2,3,'a') # (2, 3, 'a')

Scatter
The complement of gather is scatter. If you have a sequence of values and you want to
pass it to a function as multiple arguments, you can use the * operator.
Example: divmod takes exactly two arguments; it doesn’t work with a tuple:
>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1

But if you scatter the tuple, it works:


t = (7, 3)
quot, rem = divmod(*t)
print(quot) #2
print(rem) #1

DICTIONARIES
Dictionaries are one of Python‘s best features; they are the building blocks of many
efficient and elegant algorithms.
A Dictionary is a Mapping
A dictionary is like a list, but more general. In a list, the indices have to be integers; in a
dictionary they can be (almost) any type.
A dictionary contains a collection of indices, which are called keys, and a collection of values. Each
key is associated with a single value. The association of a key and a value is called a key-value pair or
sometimes an item.
In mathematical language, a dictionary represents a mapping from keys to values, so you
can also say that each key ―maps to a value. As an example, we‘ll build a dictionary that maps from
English to Tamil words, so the keys and the values are all strings.
The function dict creates a new dictionary with no items. Because dict is
the name of a built-in function, you should avoid using it as a variable name.

Create Dictionary
> eng_tam=dict()
> eng_tam
{}
The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you
can use square brackets:
>>> eng_tam['two']='irantu'
This line creates an item that maps from the key 'two' to the value 'irantu'. If we print the
dictionary again, we see a key-value pair with a colon between the key and value:
> eng_tam
> {'two':'irantu’}
This output format is also an input format. For example, you can create a new dictionary with
three items:
> eng_tam={'two':'irantu','three':'munru','four':'nanku'}
But if you print eng_tam, you might be surprised:
>>> eng_tam
{'four': 'nanku', 'two': 'irantu', 'three': 'munru'}
The order of the key-value pairs might not be the same. If you type the same example on your
computer, you might get a different result. In general, the order of items in a dictionary is
unpredictable.
But that‘s not a problem because the elements of a dictionary are never indexed with integer
indices. Instead, you use the keys to look up the corresponding values:
> eng_tam['two']
> 'irantu'
The key 'two' always maps to the value ' irantu ' so the order of the items doesn‘t matter. If
the key isn‘t in the dictionary, you get an exception:
> eng_tam['five']
KeyError: 'five'
The len function works on dictionaries; it returns the number of key-value pairs:
> len(eng_tam)
3

The in operator works on dictionaries, too; it tells you whether something appears as a key
in the dictionary (appearing as a value is not good enough).
> 'two'in eng_tam
True
> 'irantu' in
> eng_tam
> False

To see whether something appears as a value in a dictionary, you can use the method
values, which returns a collection of values, and then use the in operator:
> meaning = eng_tam.values()
> 'irantu' in meaning
True
The in operator uses different algorithms for lists and dictionaries. For lists, it searches the
elements of the list in order. As the list gets longer, the search time gets longer in direct proportion.
For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the in
operator takes about the same amount of time no matter how many items are in the dictionary.
Dictionary as a Collection of Counters
Suppose you are given a string and you want to count how many times each letter appears.
There are several ways you could do it:
1. You could create 26 variables, one for each letter of the alphabet. Then you could traverse the
string and, for each character, increment the corresponding counter, probably using a chained
conditional.
2. You could create a list with 26 elements. Then you could convert each character to a number
(using the built-in function ord), use the number as an index into the list, and increment the ap-
propriate counter.
3. You could create a dictionary with characters as keys and counters as the corresponding values.
The first time you see a character, you would add an item to the dictionary. After that you would
increment the value of an existing item.
Each of these options performs the same computation, but each of them implements that computation
in a different way.
An implementation is a way of performing a computation; some implementations are better
than others. For example, an advantage of the dictionary implementation is that we don‘t have to
know ahead of time which letters appear in the string and we only have to make room for the letters
that do appear. Here is what the code might look like:
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d

The name of the function is histogram, which is a statistical term for a collection of counters (or
frequencies). The first line of the function creates an empty dictionary. The for loop traverses the
string. Each time through the loop, if the character c is not in the dictionary, we create a new item with
key c and the initial value 1 (since we have seen this letter once). If c is already in the dictionary we
increment d[c].
Here‘s how it works:
>>> h=histogram('python programmimg')
>>> h
{'a': 1, ' ': 1, 'g': 2, 'i': 1, 'h': 1, 'm': 3, 'o': 2, 'n': 1, 'p': 2, 'r': 2, 't': 1, 'y': 1}
The histogram indicates that the letters 'a ' and ' ' appear once; 'g' appears twice, and
so on. Dictionaries have a method called get that takes a key and a default value. If the
key appears in the dictionary, get returns the corresponding value; otherwise it returns
the default value. For example:
> h = histogram('a')
> h
{'a': 1}
> h.get('a', 0)
1
> h.get('b', 0)
0
>
Looping and Dictionaries
If you use a dictionary in a for statement, it traverses the keys of the dictionary. For example,
print_hist prints each key and the corresponding value:
def print_hist(h):
for c in h:
print(c, h[c])
Here‘s what the output looks like:
> h = histogram('programming')
> print_hist(h)
('a', 1)
('g', 2)
('i', 1)
('m', 2)
('o', 1)
('n', 1)
('p', 1)
('r', 2)
Again, the keys are in no particular order. To traverse the keys in sorted order,
you can use the built-in function sorted:
for key in sorted(h):
print(key, h[key])
('a', 1)
('g', 2)
('i', 1)
('m', 2)
('n', 1)
('o', 1)
('p', 1)
('r', 2)
Reverse Lookup
Given a dictionary d and a key k, it is easy to find the corresponding value v =
d[k]. This operation is called a lookup.
But what if you have v and you want to find k? You have two problems: first, there might be
more than one key that maps to the value v. Depending on the application, you might be able to pick
one, or you might have to make a list that contains all of them. Second, there is no simple syntax to do
a reverse lookup; you have to search.
Here is a function that takes a value and returns the first key that maps to that
value:
def reverse_lookup(d, v):
for k in d:
if d[k] == v:
return k
raise LookupError()

This function is yet another example of the search pattern, but it uses a feature we haven‘t seen
before, raise. The raise statement causes an exception; in this case it causes a LookupError, which is
a built-in exception used to indicate that a lookup operation failed.
If we get to the end of the loop, that means v doesn‘t appear in the dictionary as a value, so we
raise an exception.
Here is an example of a successful reverse lookup:
> h = histogram('programming')
> key = reverse_lookup(h, 2)
> key
'g'
And an unsuccessful one:
>>> key = reverse_lookup(h, 3)
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
key = reverse_lookup(h, 3)
File "G:\class\python\code\dictionary.py", line 22, in reverse_lookup raise LookupError()
LookupError
The effect when you raise an exception is the same as when Python raises one: it prints a
traceback and an error message. The raise statement can take a detailed error message as an optional
argument. For example:
> raise LookupError('value does not appear in the dictionary') Traceback
(most recent call last):
File "<stdin>", line 1, in ?
LookupError: value does not appear in the dictionary
A reverse lookup is much slower than a forward lookup; if you have to do it often, or if the
dictionary gets big, the performance of your program will suffer.

Dictionaries and Lists


Lists can appear as values in a dictionary. For example, if you are given a dictionary that
maps from letters to frequencies, you might want to invert it; that is, create a dictionary that maps
from frequencies to letters. Since there might be several letters with the
same frequency, each value in the inverted dictionary should be a list of letters. Here is
a function that inverts a dictionary:

def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse

Each time through the loop, key gets a key from d and val gets the corresponding value. If val is
not in inverse, that means we haven‘t seen it before, so we create a new item and initialize it with a
singleton (a list that contains a single element). Otherwise we have seen this value before, so we
append the corresponding key to the list. Here is an example:
> hist = histogram('programming')
> hist
{'a': 1, 'g': 2, 'i': 1, 'm': 2, 'o': 1, 'n': 1, 'p': 1, 'r': 2}
> inverse = invert_dict(hist)
> inverse
{1: ['a', 'i', 'o', 'n', 'p'], 2: ['g', 'm', 'r']}
Lists can be values in a dictionary, as this example shows, but they cannot
be keys. Here‘s what happens if you try:
> t = [1, 2, 3]
> d = dict()
> d[t] = 'oops'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list objects are unhashable

Advanced List Processing - List Comprehension


Python supports a concept called "list comprehensions". It can be used to construct lists in a
very natural, easy way, like a mathematician is used to do. Following function takes a list of strings,
maps the string method capitalize to the elements, and returns
a new list of strings:
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res

We can write this more concisely using a list comprehension:

def capitalize_all(t):
return [s.capitalize() for s in t]

The bracket operators indicate that we are constructing a new list. The expression inside
the brackets specifies the elements of the list, and the for clause indicates what sequence we are
traversing.
The syntax of a list comprehension is a little awkward because the loop variable, s in this
example,
\ appears in the expression before we get to the definition.
List comprehensions can also be used for filtering. For example, this function selects only
the elements of t that are upper case, and returns a new list:
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
return res
We can rewrite it using a list comprehension
def only_upper(t):
return [s for s in t if s.isupper()]
List comprehensions are concise and easy to read, at least for simple expressions. And
they are usually faster than the equivalent for loops, sometimes much faster.
ILLUSTRATIVE PROGRAMS
Sorting
It is an operation in which all the elements of a list are arranged in a predetermined order.
The elements can be arranged in a sequence from smallest to largest such that every element is less
than or equal to its next neighbour in the list. Such an arrangement is called ascending order.
Assuming an array or List containing N elements, the ascending order can be defined by the following
relation:
List[i] <= List [i+1], 0 < i < N-1
Similarly in descending order, the elements are arranged in a sequence from largest to
smallest such that every element is greater than or equal to its next neighbor in the list. The
descending order can be defined by the following relation:
List[i] >= List [i+1], 0 < i <N-1
It has been estimated that in a data processing environment, 25 per cent of the time is
consumed in sorting of data. Many sorting algorithms have been developed. Some of the most popular
sorting algorithms that can be applied to arrays are in-place sort algorithm. An in-place algorithm is
generally a comparison- based algorithm that stores the sorted elements of the list in the same array as
occupied by the original one. A detailed discussion on sorting algorithms is given in subsequent
sections.
4.4.2 Selection Sort
It is a very simple and natural way of sorting a list. It finds the smallest element in the list
and exchanges it with the element present at the head of the list as shows in Figure 4.3

Figure 4.3 Selection sort (first pass)


It may be note from Figure 4.3 that initially, whole of the list was unsorted. After the
exchange of the smallest with the element on the list, the list is divided into two parts: sorted and
unsorted.
Now the smallest is searched in the unsorted part of the list, i.e., ’2’ and exchange with the
element at the head of unsorted part,
i.e., “20” as shown in Figure 4.4.

Figure 4.4 Selection sort (second pass)


This process of selection and exchange (i.e., a pass) continues in this fashion until all the
elements in the list are sorted (see Figure 4.5.). Thus, in selection sort, two steps are important –
selection and exchange.
From Figure 4.4 and Figure 4.5, it may be observed that it is a case of nested loops. The
outer loop is required for passes over the list and inner loop for searching smallest element within the
unsorted part of the list. In fact, for N number of elements, N-1 passes are made.
An algorithm for selection sort is given below. In this algorithm, the elements of a list
stored in an array called LIST[] are sorted in ascending order. Two variables called Small and Pos are
used to locate the smallest element in the unsorted part of the list. Temp is the variable used to
interchange the selected element with the first element of the unsorted part of the list.
Algorithm SelectionSort()
1. For I= 1 to N-1 #Outer Loop
1.1 small = List[I]
1.2
Pos = I
1.3
For J=I+1 to N # Inner Loop
1.3.1 if (List[J] < small)
1.3.1.1 small = List[J]
1.3.1.2 Pos = J #Note the position of the smallest

1.4 Temp= List[I] # Exchange Smallest with the


Head
1.5 List[I] = List [Pos]
1.6List [Pos] = Temp
2. Print the sorted list
Figure 4.5 Selection sort
Program to sort a List in ascending order using Selection Sort
data = []
print('Selection Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate Steps :')
for i in range(0,n-1):
small=int(data[i])
pos=i
for j in range(i+1,n):

if int(data[j])<small:
small=int(data[j])
pos=j
temp=data[i]
data[i]=data[pos]
data[pos]=temp
print(data)
print('Sorted Array :')
print(data)
Output
Selection Sort :
Enter Number of Elements in the Array: 5
Enter the Element 1 :4

Enter the Element 2 :3


Enter the Element 3 :6
Enter the Element 4 :8
Enter the Element 5 :1
Original Array :
['4', '3', '6', '8', '1']
Intermediate Steps :
['1', '3', '6', '8', '4']
['1', '3', '6', '8', '4']
['1', '3', '4', '8', '6']
['1', '3', '4', '6', '8']
Sorted Array :
['1', '3', '4', '6', '8']

Insertion Sort

This algorithm mimics the process of arranging a pack of playing cards; the first two cards are put in
correct relative order. The third is inserted at correct place relative to the first two. The fourth card is
inserted at the correct place relative to the first three, and so on.

Given a list of numbers, it divides the list into two part – sorted part and unsorted part. The first
element becomes the sorted part and the rest of the list becomes the unsorted part as Shown in Figure
4.6. It picks up one element from the front of the unsorted part as shown in Figure 4.6. It picks up one
element from the front of the unsorted part and inserts it in proper position in the sorted part of the
list. The insertion action is repeated till the unsorted part is exhausted.

Figure 4.6 Insertion sort


It may be noted that the insertion operation requires following steps:
Steps

1. Scan the sorted part to find the place where the element, from unsorted part, can be inserted.
While scanning, shift the elements towards right to create space.
2. Insert the element, from unsorted part, into the created space.
This algorithm for the insertion sort is given below. In this algorithm, the elements of a list
stored in an array called List[] are sorted in an ascending order. The algorithm uses two loops – the
outer For loop and inner while loop. The inner while loop shifts the elements of the sorted part by one
step to right so that proper place for incoming element is created. The outer For loop inserts the
element from unsorted part into the created place and moves to next element of the unsorted part.
Algorithm
insertSort()
#The first element becomes the
1. For I = 2 to N sorted part

Temp = List[I] #Save the element from unsorted


1.1 part into temp
1.2 J = I-1
1.3 While(Temp < = List[J] AND J >=0)
1.3.1 List[J+I] = List[J] #Shift elements
towards right
1.3.
2 J = J-I
1.4 List [J+I] = Temp
2. Print the list
3. Stop
Program to sort a List in ascending order using Selection Sort
data = []
print('Insertion Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate Steps :')
for i in range(1,n):
temp=int(data[i])
j=i-1
while temp<int(data[j]) and j>=0:
data[j+1]=data[j]
j=j-1
data[j+1]=temp
print(data)
print('Sorted Array is:')
print(data)

Output

Insertion Sort :
Enter Number of Elements in the Array: 5
Enter the Element 1 :3
Enter the Element 2 :5
Enter the Element 3 :2
Enter the Element 4 :8
Enter the Element 5 :1
Original Array :
['3', '5', '2', '8', '1']
Intermediate Steps :
['3', '5', '2', '8', '1']
['2', '3', '5', '8', '1']
['2', '3', '5', '8', '1']
['1', '2', '3', '5', '8']
Sorted Array is:
['1', '2', '3', '5', '8']

4.4.4 Merge Sort


This method uses following two concepts:

 If a list is empty or it contains only one element, then the list is already sorted. A list that con-
tains only one element is also called singleton.
 It uses old proven technique of ‗divide and conquer‘ to recursively divide the list
into sub-lists until it is left with either empty or singleton lists.
In fact, this algorithm divides a given list into two almost equal sub-lists. Each sub-list,
thus obtained, is recursively divided into further two sub-lists and so on till singletons or empty lists
are left as shown in Figure 4.7.
Since the singleton and empty list are inherently sorted, the only step left is to merge the
singletons into sub-lists containing two elements each (see figure 4.7) which are further merged into
sub-lists containing four elements each and so on. This merging operation is recursively carried out
till a final merged list is obtained as shown in figure 4.8.

Figure 4.8 Second step of merge sort (merge)


Note: The merge operation is a time consuming and slow operation. The working of merge operation
is discussed in the next section.
Merging of lists It is an operation in which two ordered lists are merged into a single ordered list. The
merging of two lists PAR1 and PAR2 can be done by examining the elements at the head of two lists
and selecting the smaller of the two. The smaller element is then stored into a third list called
mergeList. For example, consider the lists PAR1 and PAR2 given the figure 4.9. Let Ptr1, Ptr2, and
Ptr3 variables point to the first locations of lists PAR1, PAR2 and PAR3, respectively. The comparison
of PAR1[Ptr1] and PAR2[Ptr2]
shows that the element of PAER1 (i.e., ‗2‘) is smaller. Thus, this element will be placed in the
mergeList as per the following operation:
Figure 4.9 Merging of lists (first step)
mergeList[Ptr3] S= PAR1[Ptr1];
Ptr1++;
Ptr3++;
Since an element from the list PAR1 has been taken to mergeList, the variable Ptr1 is
accordingly incremented to point to the next location in the list. The variable Ptr3 is also incremented
to point to next vacant location in mergeList.
This process of comparing, storing and shifting is repeated till both the lists are merged
and stored in mergeList as shown in figure 4.10.

Figure 4.10 Merging of lists (second step)


It may be noted here that during this merging process, a situation may arise when we run
out of elements in one of the lists. We must, therefore, stop the merging process and copy rest of the
elements from unfinished list into the final list.
The algorithm for merging of lists is given below. In this algorithm, the two sub-lists are
part of the same array List[]. The first sub-list in locations List[lb] to List[mid] and the second sub-list
is stored in locations List [mid+1] to List [ub] where lb and ub mean lower and upper bounds of the
array, respectively.
Algorithm merge (List, lb, mid, ub)

1. ptr1 =lb # index of first list


2. ptr2 = mid # index of second list
3. ptr3 = lb #index of merged list
while ((ptr1 < mid) && ptr2
4. <= ub) #merge the lists
4.1 if (List[ptr1 <=
List[ptr2])

4.1.1 mergeList[ptr3] = #element from firstlist is


List[ptr1] taken
#move to next element in
4.1.2 ptr1++ the list
4.1.3 ptr3++

4.2 else
4.2.1 mergeList[ptr3] = #element from second list
List[ptr2] is taken
#move to next element in
4.2.2 ptr2++ the list
4.2.3 ptr3++

5. while(ptr1 < mid) #copy remaining first list


5.1 mergeList [ptr3] =
List[ptr1]
5.2 ptr1++
5.3 ptr3++
}

#copy remaining second


6. while (ptr2 <= ub) list
6.1 mergeList [ptr3] =
List[ptr2]
6.2 ptr2++
6.3 ptr3++

#copy merged list back into


7. for(i=lb; i<ptr3; i++) original list

7.1 List[i] = mergeList[i]

8. Stop
It may be noted that an extra temporary array called mergedList is required to store the
intermediate merged sub-lists. The contents of the mergeList are finally copied back into the original
list.
The algorithm for the merge sort is given below. In this algorithm, the elements of a list
stored in a array called List[] are sorted in an ascending order. The algorithm has two parts-
mergeSort and merge. The merge algorithm, given above, merges two given sorted lists into a third
list, which is also sorted. The mergeSort algorithm takes a list and stores into an array called List[]. It
uses two variables lb and ub to keep track of lower and upper bounds of list or sub-lists as the case
may be. It recursively divides the list into almost equal parts till singleton or empty lists are left. The
sub-lists are recursively merged through merge algorithm to produce final sorted list.
Algorithm mergeSort (List, lb, ub)
1. if (lb<ub)
#divide the list into two
1.1mid = (lb+ub)/2 sub-lists
1.2 mergeSort(List, lb,
mid) #sort the left sub-list
1.3 mergeSort(List,
mid+1, ub) #sort the right sub-list
1.4 merge(List, lb, mid+1,
ub) #merge the lists
2. Stop
Program to sort a List in ascending order using Merge Sort def
mergeSort(alist):
print(Splitting" ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if int(lefthalf[i]) < int(righthalf[j]):
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print(Merging" ",alist)
data = []
print('Merge Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate Steps :')
mergeSort(data)
print('Sorted Array is:')
print(data)

Output

Merge Sort :
Enter Number of Elements in the Array: 5
Enter the Element 1 :4
Enter the Element 2 :8
Enter the Element 3 :2
Enter the Element 4 :9
Enter the Element 5 :1
Original Array :
['4', '8', '2', '9', '1']
Intermediate Steps :
('Splitting ', ['4', '8', '2', '9', '1'])
('Splitting ', ['4', '8'])
('Splitting ', ['4'])
('Merging ', ['4'])
('Splitting ', ['8'])
('Merging ', ['8'])
('Merging ', ['4', '8'])
('Splitting ', ['2', '9', '1'])
('Splitting ', ['2'])
('Merging ', ['2'])
('Splitting ', ['9', '1'])
('Splitting ', ['9'])
('Merging ', ['9'])
('Splitting ', ['1'])
('Merging ', ['1'])
('Merging ', ['1', '9'])
('Merging ', ['1', '2', '9'])
('Merging ', ['1', '2', '4', '8', '9'])
Sorted Array is:
['1', '2', '4', '8', '9']
4.4.5 Quick Sort
This method also uses the techniques of ‘divide and conquer’. On the basis of a selected
element (pivot) from of the list, it partitions the rest of the list into two parts- a sub-list that contains
elements less than the pivot and other sub-list containing elements greater than the pivot. The pivot is
inserted between the two sub-lists. The algorithm is recursively applied to the sub-lists until the size
of each sub-list becomes 1, indicating that the whole list has become sorted.
Consider the list given in figure 4.11. Let the first element (i.e., 8) be the pivot. Now the rest
of the list can be divided into two parts- a sub-list that contains elements less ‗8‘ and the other sub-list
that contains elements greater than‘8‘ as shown in figure 4.11.
Now this process can be recursively applied on the two sub-lists to completely sort the whole
list. For instance, ‘7’becomes the pivot for left sub-lists and ‘19‘ becomes pivot for the right sub-lists.
Note: Two sub-lists can be safely joined when every element in the first sub-list is smaller than every
element in the second sub-list. Since ‘join’ is a faster operation as compared to a ‘merge’ operation,
this sort is rightly named as a quick sort’.

Figure 4.11 Quick Sort


The algorithm for the quick sort is given below:
In this algorithm, the elements of a list, stored in an array called List[], are sorted in an
ascending order. The algorithm has two parts- quicksort and partition. The partition algorithm divides
the list into two sub-lists around a pivot. The quick sort algorithm takes a list and stores it into an
array called List[]. It uses two variables lb and ub to keep track of lower and upper bounds of list or
sub-lists as the case may be. It employs partition algorithm to sort the sub-lists.
Algorithm quickSort()
#set lower
1. Lb 50 bound
#set upper
2. ub = N-1 bound
3. pivot = List[lb]
4. lb++
5. partition (pivot, List, lb, ub)
Algorithm partition (pivot, List, lb, ub)

1. i = lb
2. j=ub
3. while(i<=j)

#travel the list from lb till an element greater than the pivot is found 3.1 while
(List[i] <= pivot) i++
#travel the list from ub till an element smaller than the pivot is found 3.2 while
(List[j]> pivot) j--
3.3 if (i <= j) #exchange the elements

3.3.1 temp =
List[i]
List[i] =
3.3.2 List[j]
List[j] =
3.3.3 temp
#place the pivot at mid of the sub-
4. temp =List[j] lists
5. List[j] = List[lb-1]
6. List[lb-1] = temp
if (j>lb) quicksort (List,
7. lb, j-1) #sort left sub-list
if(j<ub) quicksort (List, #sort the right
8. j+1, ub) sub-lists
Program to sort a List in ascending order using
def quicksort(myList, start, end):
if start < end:
pivot = partition(myList, start, end)
print(myList)
quicksort(myList, start, pivot-1)
quicksort(myList, pivot+1, end)
return myList
def partition(myList, start, end):
pivot = int(myList[start])
left = start+1
right = end
done = False
while not done:
while left <= right and int(myList[left]) <= pivot:
left = left + 1
while int(myList[right]) >= pivot and right >=left:
right = right -1
if right < left:
done= True
else:
temp=myList[left]
myList[left]=myList[right]
myList[right]=temp
temp=myList[start]
myList[start]=myList[right]
myList[right]=temp
return right

data = []
print('Quick Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate Steps :')
quicksort(data,0,n-1)
print('Sorted Array is:')
print(data)

Output

Quick Sort :
Enter Number of Elements in the Array: 8
Enter the Element 1 :8
Enter the Element 2 :5
Enter the Element 3 :6
Enter the Element 4 :9
Enter the Element 5 :4
Enter the Element 6 :19
Enter the Element 7 :7
Enter the Element 8 :2
Original Array :
['8', '5', '6', '9', '4', '19', '7', '2']
Intermediate Steps :
['7', '5', '6', '2', '4', '8', '19', '9']
['4', '5', '6', '2', '7', '8', '19', '9']
['2', '4', '6', '5', '7', '8', '19', '9']
['2', '4', '5', '6', '7', '8', '19', '9']
['2', '4', '5', '6', '7', '8', '9', '19']
Sorted Array is:
['2', '4', '5', '6', '7', '8', '9', '19']

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy