Unit - 1 INTRODUCTION TO PYTHON - ECE
Unit - 1 INTRODUCTION TO PYTHON - ECE
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.
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.
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.
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.
[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)
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.
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
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
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
Eg:
b=True
a=1 if b else None
Output:
1
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
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
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
Output2:
Enter a number: 128
The number is not an armstrong number
Output:
Enter the limit:5
Sum of first n natural nos:15
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
Syntax:
Pass
Example:
Output:
Pass: h
Pass: e
Pass: l
Pass: l
Pass: o
Done
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:
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
Enter a vowel: x
Not a vowel. Try again
Enter a vowel: a
Finally entered a vowel
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.
Output:
Enter A=2
Enter B=3
The sum=5
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
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.
Op: Found
Eg: Eg: Eg:
'u' in "stars" 'v' not in" stars" "vi" in victory
False True True
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]])
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']
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
> Returns true,if the first string >>> “abc" > "Abc"
is greater than the second >>>True
string
>= Returns true,if the first string >>> “aBC" >= "ABC"
is greater than or equal to the >>>True
second string
EXAMPLE PROGRAM :
Output:
Enter a number: 3
Enter an exponent: 2
9
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
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)
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
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.
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.
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
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:
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
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
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.
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
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
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
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.
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
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']
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.
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++
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’.
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']