It22dsp PDF
It22dsp PDF
ON
DATA STRUCTURES USING PYTHON
OBJECTIVES:
UNIT I
Introduction to Python, Installation and Working with Python, Understanding Python
variables Python basic Operators, Understanding python blocks, Python Data Types:
Declaring and using Numeric data types: int, float,complex,Using string data type and string
operations.
UNIT II
Control Flow- if, if-elif-else,loops ,For loop using ranges, string ,Use of while loops in
python,Loop manipulation using pass, continue, break and else,Programming using Python
conditional and loops block,Python arrays.
UNIT III
Functions -Calling Functions, Passing Arguments, Keyword Arguments,Default Arguments,
Variable-length arguments, Anonymous Functions, Fruitful Functions(Function Returning
Values), Scope of the Variables in a Function - Global and Local Variables.Powerful Lamda
function in python.
UNIT IV
Data Structures-List Operations, Slicing, Methods; Tuples, Sets, Dictionaries,Sequences.
Comprehensions,Dictionary manipulation, list and dictionary in build functions
UNIT V
Sorting:BubbleSort,SelectionSort,InsertionSort,Mergesort,Quicksort.LinkedLists,Stacks,Que
ues
OUTCOMES:
INDEX
S. No Topic Page no
Unit
1 Introduction to Python 1
I
5 I 16
Using string data type and string operations.
6 II Control Flow 19
7 II Loops 33
8 II Python arrays 37
9 III Functions 41
12 IV Data Structures 62
13 IV Comprehensions 82
14 V Sorting 86
15 V 97
Linked Lists, Stacks, Queues
UNIT - I
INTRODUCTION TO PYTHON:
Python is a widely used general-purpose, high level programming language. It was initially designed by
Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for
emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our programs.
There are certain online interpreters like https://ide.geeksforgeeks.org/, http://ideone.com/ or
http://codepad.org/ that can be used to start Python without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software
from http://python.org/downloads/
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python
3. It’s free (open source)
Downloading python and installing python is free and easy
4. It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
5. It’s Portable
Python runs virtually every major platform used today
As long as you have a compaitable python interpreter installed, python programs will run in
exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate form called byte code, which
the interpreter then reads.
This gives python the development speed of an interpreter without the performance loss
inherent in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it popular.
Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated Development
Environment) which is installed when you install the python software from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
Python’s traditional runtime execution model: Source code you type is translated to byte code, which is
then run by the Python Virtual Machine (PVM). Your code is automatically compiled, but then it is
interpreted.
PVM
m.py m.pyc
Without passing python script file to the interpreter, directly execute code to Python prompt. Once you’re
inside the python interpreter, then you can start.
hello world
>>> x=[0,1,2]
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python interpreter uses to
indicate that it is ready. If the programmer types 2+6, the interpreter replies 8.
Alternatively, programmers can store Python script source code in a file with the .py extension, and use the
interpreter to execute the contents of the file. To execute the script by the interpreter, you have to tell the
interpreter the name of the file. For example, if you have a script name MyFile.py and you're working on
Unix, to run the script you have to type:python MyFile.py
Example:
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable.
For example −
c = "John" # A string
print (a)
print (b)
100
1000.0
John
Multiple Assignment:
For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables.
For example −
a,b,c = 1,2,"mrcet“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string
object with the value "john" is assigned to the variable c.
Output Variables:
Variables do not need to be declared with any particular type and can even change type after they have been
set.
Output: mrcet
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output
Python is awesome
DATA STRUCTURES USING PYTHON Page 6
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome
Operators are used to perform operations on variables and values. Python divides the operators in the
following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
Assignment operators
= x=5 x=5
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
Comparison operators
== Equal x == y
!= Not equal x != y
Logical operators
not Reverse the result, returns False not(x < 5 and x < 10)
if the result is true
is not Returns true if both variables are not the same object x is not y
Membership operators
not in Returns True if a sequence with the specified value is not x not in y
present in the object
Bitwise operators
<< Zero fill left shift Shift left by pushing zeros in from the right and let the
leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off
Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses
indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented line.
The amount of indentation is up to you, but it must be consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.
print(i)
if i == 5:
break
output:
The enforcement of indentation in Python makes the code look neat and clean. This results into Python
programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code
more readable. For example:
>>> if True:
print('Hello')
a=5
Output: Hello
Output: Hello
The following are code blocks: A module is a code block. A function body is a code block. A class
definition is a code block. Each command typed interactively is a separate code block; a script file (a file
given as standard input to the interpreter or specified on the interpreter command line the first argument) is a
code block; a script command (a command specified on the interpreter command line with the `-c' option) is
a code block. The file read by the built-in function execfile() is a code block. The string argument passed to
the built-in function eval() and to the exec statement is a code block. And finally, the expression read and
evaluated by the built-in function input() is a code block.
Some examples:
1. if-statement
pwd=input("enter string")
if pwd == 'mrcet':
print('Logging on ...')
else:
print('Incorrect password.')
print('All done!')
Output:
===============================================
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/iff.py
==============================================
Logging on ...
All done!
2. if/elif-statements
if age <= 2:
print(' free')
else:
print('adult fare')
Output:
===============================================
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/if1.py
==============================================
child fare
3. Functions
def my_college():
print("Hello mrcet")
my_college()
Output:
===============================================
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/if2.py
==============================================
Hello mrcet
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value
and his or her address is stored as alphanumeric characters. Python has various standard data types that are
used to define the operations possible on them and the storage method for each of them.
Number data types store numeric values. Number objects are created when you assign a value to them.
For example:
var1 = 1
var2 = 10
You can delete a single object or multiple objects by using the del statement.
For example:
del var
del var_a, var_b
Python supports four different numerical types −
• long (long integers, they can also be represented in octal and hexadecimal)
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and
y are the real numbers and j is the imaginary unit.
Example: 1
x=1 # int
y = 2.8 # float
z = 1j # complex
# To verify the type of any object in Python, use the type() function:
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
Example: 2
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Python Casting:
There may be times when you want to specify a type on to a variable. This can be done with casting. Python
is an object-orientated language, and as such it uses classes to define data types, including its primitive
types. Casting in python is therefore done using constructor functions:
int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous
whole number), or a string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal (providing the
string represents a float or an integer)
Examples:
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Print(x)
Print(y)
Print(z)
Output:
1
2
3
Floats:
Print(x)
Print(y)
Print(z)
Print(w)
Output:
1.0
2.8
3.0
4.2
Strings:
Print(x)
Print(y)
Print(z)
s1
2
3.0
1. Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes.
• Strings can be output to screen using the print function. For example: print("hello").
2. Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
3. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.
4. Like many other popular programming languages, strings in Python are arrays of bytes representing
Unicode characters. However, Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to access elements of the string.
Examples:
Get the character at position 1 (remember that the first character has the position 0):
Output:
b = "Hello, World!"
print(b[2:5])
Output:
llo
• The strip() method removes any whitespace from the beginning or the end:
a = 'Hello,World!'
print(a.strip('He'))
b = 'Hello,World! Hello'
print(b.strip('Hello'))
Output:
llo,World!
droid is awesome
,World!
a = "Hello, World!"
print(len(a))
Output:
13
a = "Hello, World!"
print(a.lower())
Output:
hello, world!
a = "Hello, World!"
print(a.upper())
Output:
HELLO, WORLD!
a = "Hello, World!"
print(a.replace("H", "J"))
Output:
Jello, World!
a = "Hello, World!"
b = a.split(",")
print(b)
Output:
['Hello', 'World!']
For example −
Output:
Hello World!
llo
llo World!
Hello World!TEST
if
if Statement Syntax:
if test expression:
statement(s)
if Statement Flowchart:
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if1.py
3 is greater
done
-1 a is smaller
Syntax of if - else :
if test expression:
Body of if stmts
else:
If - else Flowchart :
Example of if - else:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number 2
a is smaller than the input given
If – elif - else:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number5
enter the number2
enter the number9
a is greater
>>>
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/nestedif.py
Enter a number: -1
Negative number
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/nestedif.py
Enter a number: 5
Positive number
>>>
Enter a number: 0
Zero
LOOPS:
Statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on. There may be a situation when you need to execute a block of code several number of
times.
Programming languages provide various control structures that allow for more complicated execution
paths. A loop statement allows us to execute a statement or group of statements multiple times. The
following diagram illustrates a loop statement −
Flow chart:
1. while loop
2. for loop
3. Nested loops
These control statements change execution from its normal sequence. Python supports the following:
Break statement
Continue statement
Pass statement
Python for loop is used for repeated execution of a group of statements for the desired number of times. It
iterates over the items of lists, tuples, strings, the dictionaries and other iterable objects
Sample Program:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/fr.py
16
36
121
400
Flowchart:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fr3.py
These are the first four prime numbers
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/dic.py
Keys are:
ces
it
ece
Values are:
block1
block2
block3
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr.py
M
R
C
E
T
range(start, end, step_size) : will generate numbers from start to end with step_size as incremental
factor in each iteration. step_size is default if not explicitly mentioned.
Examples:
x=10
for i in range(x):
print(i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/fr2.py
0
1
2
3
4
5
6
7
8
9
-----------------------------
x=10
for i in range(6,x):
print(i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/fr2.py
6
7
DATA STRUCTURES USING PYTHON Page 27
8
9
-------------------------------
x=10
for i in range(2,13,2):
print(i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/fr2.py
2
4
6
8
10
12
STRING:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr.py
M
R
C
E
T
Using range():
------------------------------------
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/rn.py =
the college name is
DATA STRUCTURES USING PYTHON Page 28
M
R
C
E
T
----------------------------------
#declare a string to iterate over
college = 'MRCET'
print("To print the portion of string")
#Iterating over the string
for i in college[0:3:1]:
print (i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr1.py
To print the portion of string
M
R
C
---------------------------------------
#declare a string to iterate over
college = 'MRCET'
print("To print the string in reverse")
#Iterating over the string
for i in college[ : :-1]:
print (i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr2.py
To print the string in reverse
T
E
C
R
M
--------------------------------------
#declare a string to iterate over
college = 'MRCET'
print("To print the string in reverse using index")
#Iterating over the string
i=len(college) - 1
while i > 0:
print(college[i])
i=i-1
#for i in college[ : :-1]:
#print (i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr3.py
DATA STRUCTURES USING PYTHON Page 29
To print the string in reverse using index
T
E
C
R
-----------------------------------------
#declare a string to iterate over
i=1
college = 'MRCET'
print("To print the string in reverse using negative index")
#Iterating over the string
while i<=len(college):
print(college[-i])
i=i+1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr4.py
To print the string in reverse using index
T
E
C
R
M
While loop:
Loops are either infinite or conditional. Python while loop keeps reiterating a block of code defined
inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is repeatedly executed as
long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a block of multiple
statements.
Syntax:
while(expression):
Statement(s)
Example Programs:
1. --------------------------------------
i=1
while i<=6:
print("Mrcet college")
i=i+1
output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh1.py
Mrcet college
Mrcet college
Mrcet college
Mrcet college
Mrcet college
Mrcet college
2. -----------------------------------------------------
i=1
while i<=3:
print("MRCET",end=" ")
j=1
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
i=1
j=1
while i<=3:
print("MRCET",end=" ")
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh3.py
4. ----------------------------------------
i=1
while (i < 10):
print (i)
i = i+1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh4.py
1
2
3
4
5
6
7
8
9
5. ---------------------------------------
a=1
b=1
while (a<10):
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh5.py
Iteration 1
Iteration 2
Iteration 3
While loop terminated
In Python, break and continue statements can alter the flow of a normal loop. Sometimes we wish to
terminate the current iteration or even the whole loop without checking test expression. The break and
continue statements are used in these cases.
Break:
The break statement terminates the loop containing it and control of the program flows to the statement
immediately after the body of the loop. If break statement is inside a nested loop (loop inside another loop),
break will terminate the innermost loop.
Flowchart:
The following shows the working of break statement in for and while loop:
Example:
Output:
M
R
C
E
T
The end
Output:
11
9
88
The number 88 is found
Terminating the loop
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop
does not terminate but continues on with the next iteration.
Flowchart:
The following shows the working of break statement in for and while loop:
Example:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cont.py
s
t
r
n
g
The end
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py
11
9
89
Pass:
In Python programming, pass is a null statement. The difference between a comment and pass statement in
Python is that, while the interpreter ignores a comment entirely, pass is not ignored.
pass is just a placeholder for functionality to be added later.
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/f1.y.py
>>>
PYTHON ARRAYS:
Array is a container which can hold a fix number of items and these items should be of the same type. Most
of the data structures make use of arrays to implement their algorithms. Following are the important terms
to understand the concept of Array.
Array Representation
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at index 6 as 70
Basic Operations
Typecode Value
b Represents signed integer of size 1 byte/td>
Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
>>>
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/arr.py
10
20
30
40
50
Accessing Array Element
We can access each element of an array using the index of the element.
Output:
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr2.py
10
30
Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on the requirement, a new
element can be added at the beginning, end, or any given index of array.
Here, we add a data element at the middle of the array using the python in-built insert() method.
Output:
============================================
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr3.py
===========================================
10
60
20
30
40
50
>>>
Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all elements of an array.
Here, we remove a data element at the middle of the array using the python in-built remove() method.
Output:
DATA STRUCTURES USING PYTHON Page 39
============================================
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr4.py
===========================================
10
20
30
50
Search Operation
You can perform a search for an array element based on its value or its index.
Here, we search a data element using the python in-built index() method.
Output:
============================================
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr5.py
===========================================
3
>>>
Update Operation
Update operation refers to updating an existing element from the array at a given index.
Here, we simply reassign a new value to the desired index we want to update.
Output:
============================================
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr6.py
===========================================
10
20
80
40
50
Function is a group of related statements that perform a specific task. Functions help break our program into
smaller and modular chunks. As our program grows larger and larger, functions make it more organized and
manageable. It avoids repetition and makes code reusable.
integer = -20
Output:
def add_numbers(x,y):
sum = x + y
return sum
Output:
The sum is 25
There are three types of Python function arguments using which we can call a function.
1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments
Syntax:
def functionname():
statements
.
.
.
functionname()
DATA STRUCTURES USING PYTHON Page 41
Function definition consists of following components:
Example:
def hf():
hello world
hf()
In the above example we are just trying to execute the program by calling the function. So it will not display
any error and no output on to the screen but gets executed.
def hf():
print("hello world")
hf()
Output:
hello world
-------------------------------
def hf():
print("hw")
hf()
hf()
hf()
DATA STRUCTURES USING PYTHON Page 42
Output:
hw
gh kfjg 66666
hw
gh kfjg 66666
hw
gh kfjg 66666
---------------------------------
def add(x,y):
c=x+y
print(c)
add(5,4)
Output:
def add(x,y):
c=x+y
return c
print(add(5,4))
Output:
-----------------------------------
def add_sub(x,y):
c=x+y
d=x-y
return c,d
print(add_sub(10,5))
Output:
(15, 5)
def hf():
return "hw"
print(hf())
Output:
hw
----------------------------
def hf():
return "hw"
hf()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu.py
>>>
-------------------------------------
def hello_f():
return "hellocollege"
print(hello_f().upper())
Output:
HELLOCOLLEGE
# Passing Arguments
def hello(wish):
return '{}'.format(wish)
print(hello("mrcet"))
mrcet
------------------------------------------------
Here, the function wish() has two parameters. Since, we have called this function with two arguments, it
runs smoothly and we do not get any error. If we call it with different number of arguments, the interpreter
will give errors.
def wish(name,msg):
wish("MRCET","Good morning!")
Output:
Below is a call to this function with one and no arguments along with their respective error messages.
----------------------------------------------
def hello(wish,hello):
print(hello("mrcet","college"))
Output:
himrcet,college
#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments according to their
position.
(Or)
If you have some functions with many parameters and you want to specify only some of them, then you can
give values for such parameters by naming them - this is called keyword arguments - we use the name
(keyword) instead of the position (which we have been using all along) to specify the arguments to the
function.
There are two advantages - one, using the function is easier since we do not need to worry about the order
of the arguments. Two, we can give values to only those parameters which we want, provided that the other
parameters have default argument values.
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
Note:
The function named func has one parameter without default argument values, followed by two parameters
with default argument values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the value 5 and c gets the
default value of 10.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the position of the argument.
Then, the parameter c gets the value of 24 due to naming i.e. keyword arguments. The variable b gets the
default value of 5.
In the third usage func(c=50, a=100), we use keyword arguments completely to specify the values. Notice,
that we are specifying value for parameter c before that for a even though a is defined before c in the
function definition.
def func(b=5, c=10,a): # shows error : non-default argument follows default argument
Output:
#Default Arguments
We can provide a default value to an argument by using the assignment operator (=)
def hello(wish,name='you'):
return '{},{}'.format(wish,name)
print(hello("good morning"))
Output:
good morning,you
---------------------------------------------
def hello(wish,name='you'):
Output:
Note: Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if we had defined
the function header above as:
------------------------------------------
print (a+b)
Output:
#Variable-length arguments
Sometimes you may need more arguments to process function then you mentioned in the definition. If we
don’t know in advance about the arguments needed in function, we can use variable-length arguments also
called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyworded
variable-length arguments and a double asterisk (**) is placed before a parameter in function which can
hold keyworded variable-length arguments.
If we use one asterisk (*) like *var, then all the positional arguments from that point till the end are
collected as a tuple called ‘var’ and if we use two asterisks (**) before a variable like **var, then all the
positional arguments from that point till the end are collected as a dictionary called ‘var’.
def wish(*names):
"""This function greets all
the person in the names tuple."""
Output:
Hello MRCET
Hello CSE
Hello SIR
Hello MADAM
#function defination
def display():
print("vandemataram")
print("i am in main")
#function call
display()
print("i am in main")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
i am in main
vandemataram
i am in main
def Fun1() :
print("function 1")
Fun1()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
function 1
def fun2(a) :
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Hello
def fun3():
return "welcome to python"
print(fun3())
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
welcome to python
def fun4(a):
return a
print(fun4("python is better then c"))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
#Program to find area of a circle using function use single return value function with argument.
pi=3.14
def areaOfCircle(r):
return pi*r*r
r=int(input("Enter radius of circle"))
print(areaOfCircle(r))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter radius of circle 3
28.259999999999998
DATA STRUCTURES USING PYTHON Page 50
#Program to write sum different product and using arguments with return value function.
def calculete(a,b):
total=a+b
diff=a-b
prod=a*b
div=a/b
mod=a%b
return total,diff,prod,div,mod
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
s,d,p,q,m = calculete(a,b)
#print("diff= ",d)
#print("mul= ",p)
#print("div= ",q)
#print("mod= ",m)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5
def biggest(a,b):
if a>b :
return a
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
big= biggest(a,b)
print("big number= ",big)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value-2
big number= 5
def biggest(a,b,c):
if a>b :
if a>c :
return a
else :
return c
else :
if b>c :
return b
else :
return c
a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))
#function call
big= biggest(a,b,c)
print("big number= ",big)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value -6
Enter c value 7
big number= 7
def result(a):
if a>40:
return "pass"
else:
return "fail"
a=int(input("Enter one subject marks"))
print(result(a))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter one subject marks 35
fail
#Write a program to display mrecet cse dept 10 times on the screen. (while loop)
def usingFunctions():
count =0
while count<10:
print("mrcet cse dept",count)
count=count+1
usingFunctions()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
mrcet cse dept 0
mrcet cse dept 1
mrcet cse dept 2
mrcet cse dept 3
mrcet cse dept 4
mrcet cse dept 5
mrcet cse dept 6
mrcet cse dept 7
mrcet cse dept 8
mrcet cse dept 9
ANONYMOUS FUNCTIONS:
print(double(5))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
10
print(add(5,4))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
9
print(biggest(20,30))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
30
We write functions that return values, which we will call fruitful functions. We have seen
the return statement before, but in a fruitful function the return statement includes a return value. This
def area(radius):
temp = 3.14 * radius**2
return temp
print(area(4))
(or)
def area(radius):
return 3.14 * radius**2
print(area(2))
Sometimes it is useful to have multiple return statements, one in each branch of a conditional:
def absolute_value(x):
if x < 0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be executed.
As soon as a return statement executes, the function terminates without executing any subsequent
statements. Code that appears after a return statement, or any other place the flow of execution can never
reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the program hits
a return statement. For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
This function is incorrect because if x happens to be 0, both conditions is true, and the function ends without
hitting a return statement. If the flow of execution gets to the end of a function, the return value is None,
which is not the absolute value of 0.
By the way, Python provides a built-in function called abs that computes absolute values.
DATA STRUCTURES USING PYTHON Page 55
# Write a Python function that takes two lists and returns True if they have at least one common
member.
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\fu1.py
True
True
None
The scope of a variable determines its accessibility and availability in different portions of a program. Their
availability depends on where they are defined. Similarly, life is a period in which the variable is stored in
the memory.
Depending on the scope and the lifetime, there are two kinds of variables in Python.
Local Variables
Global Variables
Variables or parameters defined inside a function are called local variables as their scope is limited
to the function only. On the contrary, Global variables are defined outside of the function.
Local variables can’t be used outside the function whereas a global variable can be used throughout
the program anywhere as per requirement.
The lifetime of a local variable ends with the termination or the execution of a function, whereas the
lifetime of a global variable ends with the termination of the entire program.
The variable defined inside a function can also be made global by using the global statement.
def function_name(args):
.............
global x #declaring global variable inside a function
..............
x = "global"
def f():
print("x inside :", x)
f()
print("x outside:", x)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
x inside : global
x outside: global
def f1():
y = "local"
print(y)
f1()
Output:
local
If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
The output shows an error, because we are trying to access a local variable y in a global scope whereas the
local variable only works inside f2() or local scope.
DATA STRUCTURES USING PYTHON Page 57
# use local and global variables in same code
x = "global"
def f3():
global x
y = "local"
x=x*2
print(x)
print(y)
f3()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
globalglobal
local
In the above code, we declare x as a global and y as a local variable in the f3(). Then, we use
multiplication operator * to modify the global variable x and we print both x and y.
After calling the f3(), the value of x becomes global global because we used the x * 2 to print two
times global. After that, we print the value of local variable y i.e local.
x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
local x: 10
global x: 5
Lambda functions are used along with built-in functions like filter(), map() and reduce()etc….
Filter():
#Write a program to filter() function to filter out only even numbers from the given list
myList =[1,2,3,4,5,6]
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\fu1.py
[2, 4, 6]
#Write a program for filter() function to print the items greater than 4
list1 = [10,2,8,7,5,4,3,11,0, 1]
print(list(result))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/m1.py =
[10, 8, 7, 5, 11]
Map() :
myList =[1,2,3,4,5,6,7,8,9,10]
newList = list(map(lambda x: x*2,myList))
print(newList)
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\fu1.py
# Write a program to separate the letters of the word "hello" and add the letters as items of the list.
letters = []
letters = list(map(lambda x:x,"hello"))
print(letters)
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\fu1.py
#Write a program for map() function to double all the items in the list?
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
print(list(result))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/m1.py =
[2, 4, 6, 8]
Reduce():
#Write a program to find some of the numbers for the elements of the list by using reduce()
import functools
myList =[1,2,3,4,5,6,7,8,9,10]
print(functools.reduce(lambda x,y: x+y,myList))
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\fu1.py
55
#Write a program for reduce() function to print the product of items in a list
list1 = [1,2,3,4,5]
print(product)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/m1.py =
120
Data Structures in Python provides / include Python list, Python Tuple, Python set, and Python dictionaries
with their syntax and examples.
Here in this data structure we will come to know as a way of organizing and storing data such that we can
access and modify it efficiently
List:
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
The list data type has some more methods. Here are all of the methods of list objects:
List Operations:
Del()
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
>>> x
-------------------------
>>> x.insert(4,['a',11])
>>> x
Pop: The pop() method removes the specified index, (or the last item if index is not specified) or simply
pops the last item of list and returns the item.
>>> x.pop()
>>> x
[1, 2, 10, 4, 6]
-----------------------------------
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
-----------------------
>>> x=[10,1,5,3,8,7]
>>> x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
Slicing: Slice out substrings, sub lists, sub Tuples using index.
Slicing will start from index and will go up to stop in step of steps.
Default value of start is 0,
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.
Supports all operations for sequences.
Immutable, but member objects may be mutable.
If the contents of a list shouldn’t change, use a tuple to prevent items from accidently being
added, changed, or deleted.
Tuples are more efficient than list due to python’s implementation.
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
DATA STRUCTURES USING PYTHON Page 68
(1, 2, 3)
-----------------------
>>> x=()
>>> x
()
----------------------------
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
-----------------------------
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
Access tuple items: Access tuple items by referring to the index number, inside square brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
4
Index (): Searches the tuple for a specified value and returns the position of where it
was found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y)
1
Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Set:
A set is a collection which is unordered and unindexed with no duplicate elements. In Python sets are
written with curly brackets.
Example:
>>> x={1,3,5,6}
We cannot access items in a set by referring to an index, since sets are unordered the items has
no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a
set, by using the in keyword.
Add (): To add one item to a set use the add () method. To add more than one item to a set use
the update () method.
>>> x={"mrcet","college","cse","dept"}
>>> x.add("autonomous")
>>> x
{'mrcet', 'dept', 'autonomous', 'cse', 'college'}
----
>>> x={1,2,3}
>>> x.update("a","b")
>>> x
{1, 2, 3, 'a', 'b'}
----------------
>>> x={1,2,3}
>>> x.update([4,5],[6,7,8])
>>> x
{1, 2, 3, 4, 5, 6, 7, 8}
Remove (): To remove an item from the set we use remove or discard methods.
>>> x={1, 2, 3, 'a', 'b'}
>>> x.remove(3)
Item in X: you can loop through the set items using a for loop.
>>> x={'a','b','c','d'}
>>> for item in x:
print(item)
c
d
a
b
pop ():This method is used to remove an item, but this method will remove the last item. Remember
that sets are unordered, so you will not know what item that gets removed.
>>> x={1, 2, 3, 4, 5, 6, 7, 8}
>>> x.pop()
1
>>> x
{2, 3, 4, 5, 6, 7, 8}
>>> x={2, 3, 4, 5, 6, 7, 8}
>>> x.clear()
>>> x
set()
>>> x={1,2,3,4}
>>> y={4,5,6,7}
>>> print(x|y)
{1, 2, 3, 4, 5, 6, 7}
-----------------------------
>>> x={1,2,3,4}
>>> y={4,5,6,7}
DATA STRUCTURES USING PYTHON Page 72
>>> print(x&y)
{4}
----------------------------
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> print(A-B)
{1, 2, 3}
---------------------------
>>> B = {4, 5, 6, 7, 8}
>>> A = {1, 2, 3, 4, 5}
>>> print(B^A)
{1, 2, 3, 6, 7, 8}
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.
Key-value pairs
Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(‘A’=1,’B’ =2)
Examples:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}
-------------------
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x
'mrcet'
---------------------
To access keys and values and items of dictionary:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1.keys()
dict_keys(['brand', 'model', 'year'])
>>> dict1.values()
dict_values(['mrcet', 'college', 2004])
>>> dict1.items()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])
-----------------------------------------------
>>> for items in dict1.values():
print(items)
DATA STRUCTURES USING PYTHON Page 73
mrcet
college
2004
brand
model
year
('brand', 'mrcet')
('model', 'college')
('year', 2004)
Add/change values: You can change the value of a specific item by referring to its key name
>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4
Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x:
print(key, x[key])
11
24
39
4 16
5 25
>>> for k,v in x.items():
print(k,v)
11
24
39
4 16
5 25
List of Dictionaries:
1 John
2 Smith
3 Andersson
## Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
DATA STRUCTURES USING PYTHON Page 75
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'charlie'}]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2, 'name': 'Smith', 'password': '123456'}, {'uid': 3,
'name': 'charlie', 'password': '123456'}]
## Delete a field
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password': '123456'}]
>>> x
{'name': 'John', 'password': '123456'}
Sequences:
A sequence is a succession of values bound together by a container that reflects their type. Almost every
stream that you put in python is a sequence. Some of them are:
String
List
Tuples
Range object
String: A string is a group of characters. Since Python has no provision for arrays, we simply use
strings. This is how we declare a string. We can use a pair of single or double quotes. Every string
object is of the type ‘str’.
>>> type("name")
<class 'str'>
List: A list is an ordered group of items. To declare it, we use square brackets.
>>> college=["cse","it","eee","ece","mech","aero"]
>>> college[1]
'it'
>>> college[:2]
['cse', 'it']
>>> college[:3]
['cse', 'it', 'eee']
>>> college[3:]
['ece', 'mech', 'aero']
>>> college[0]="csedept"
>>> college
['csedept', 'it', 'eee', 'ece', 'mech', 'aero']
Tuple: It is an immutable group of items. When we say immutable, we mean we cannot change a single
value once we declare it.
>>> x=[1,2,3]
>>> y=tuple(x)
>>> y
(1, 2, 3)
>>> hello=tuple(["mrcet","college"])
>>> hello
('mrcet', 'college')
Range object: A range() object lends us a range to iterate on; it gives us a list of numbers.
>>> a=range(4)
>>> type(a)
<class 'range'>
1
3
DATA STRUCTURES USING PYTHON Page 77
5
1. Indexing
Access any item in the sequence using its index.
string List
>>> x='mrcet' >>> x=['a','b','c']
>>> print(x[2]) >>> print(x[1])
c b
2. Slicing
Slice out substrings, sub lists, sub tuples using index
[start : stop : step size]
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
3. Adding/concatenation:
Combine 2 sequences of same type using +.
string List
>>> x='mrcet' + 'college' >>> x=['a','b'] + ['c']
>>> print(x) >>> print(x)
Mrcetcollege ['a', 'b', 'c']
4. Multiplying:
Multiply a sequence using *.
string List
>>> x='mrcet'*3 >>> x=[3,4]*2
>>> x >>> x
'mrcetmrcetmrcet' [3, 4, 3, 4]
5. Checking Membership:
Test whether an item is in or not in a sequence.
string List
>>> x='mrcet' >>> x=['a','b','c']
>>> print('c' in x) >>> print('a' not in x)
True False
6. Iterating:
Iterate through the items in asequence
>>> x=[1,2,3]
>>> for item in x:
print(item*2)
If we want to display the items of a given list with index then we have to use “enumerate”
keyword.
>>> x=[5,6,7]
>>> for item,index in enumerate(x):
print(item,index)
05
16
27
7. len():
It will count the number of items in a given sequence.
string List
>>> x="mrcet" >>> x=["aa","b",'c','cc']
>>> print(len(x)) >>> print(len(x))
5 4
8. min():
Finds the minimum item in a given sequence lexicographically.
string List
>>> x="mrcet" >>> x=["apple","ant1","ant"]
>>> print(min(x)) >>> print(min(x))
c ant
>>> x=["apple","ant1","ant",11]
>>> print(min(x))
9. max():
Finds the maximum item in a given sequence
string List
DATA STRUCTURES USING PYTHON Page 80
>>> x='cognizant' >>> x=["hello","yummy","zebra"]
>>> print(max(x)) >>> print(max(x))
z zebra
>>> x=["hello","yummy1","zebra1",22]
>>> print(max(x))
10. Sum:
Finds the sum of items in a sequence
>>> x=[1,2,3,4,5]
>>> print(sum(x))
15
>>> print(sum(x[-2:]))
9
11. Sorted():
Returns a new list of items in sorted order but does not change the original list.
string List
>>> x='college' >>> x=['a','r','g','c','j','z']
>>> print(sorted(x)) >>> print(sorted(x))
['c', 'e', 'e', 'g', 'l', 'l', 'o'] ['a', 'c', 'g', 'j', 'r', 'z']
12. Count():
It returns the count of an item
string List
13. Index()
Returns the index of first occurrence
string List
>>> x='college' >>> x=['a','b','a','a','c','a']
>>> print(x.index('l')) >>> print(x.index('a'))
2 0
COMPREHENSIONS:
List:
List comprehensions provide a concise way to create lists. Common applications are to make new lists
where each element is the result of some operations applied to each member of another sequence or iterable,
or to create a subsequence of those elements that satisfy a certain condition.
>>> list1=[]
list1.append(x**2)
>>> list1
(or)
>>> list1
(or)
>>> list1
>>> a=5
>>> table = [[a, b, a * b] for b in range(1, 11)]
>>> for i in table:
print(i)
[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]
Tuple:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You might expect it
For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr> at
0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a generator. The only
thing that you need to know now about a generator now is that you can iterate over it, but ONLY
ONCE.
So, given the code
a
b
c
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
Set:
Similarly to list comprehensions, set comprehensions are also supported:
DICTIONARY:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and value expressions:
Bubble Sort:
It is a simple sorting algorithm which sorts ‘n’ number of elements in the list by comparing the ach pair of
adjacent items and swaps them if they are in wrong order.
Algorithm:
1. Starting with the first element (index=0), compare the current element with the next element of a list.
2. If the current element is greater (>) than the next element of the list then swap them.
3. If the current element is less (<) than the next element of the list move to the next element.
4. Repeat step 1 until it correct order is framed.
For ex: list1= [10, 15, 4, 23, 0] so here we are comparing values again
#Write a python program to arrange the elements in ascending order using bubble sort:
list1=[9,16,6,26,0]
print("unsorted list1 is", list1)
for j in range(len(list1)-1):
for i in range(len(list1)-1):
if list1[i]>list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)
Output:
unsorted list1 is [9, 16, 6, 26, 0]
[9, 16, 6, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 26, 0]
for j in range(len(list1)-1,0,-1):
for i in range(j):
if list1[i]>list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/bubb2.py
unsorted list1 is [9, 16, 6, 26, 0]
[9, 16, 6, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 26, 0]
[9, 6, 16, 0, 26]
DATA STRUCTURES USING PYTHON Page 87
[6, 9, 16, 0, 26]
[6, 9, 16, 0, 26]
[6, 9, 0, 16, 26]
# In a different way:
list1=[9,16,6,26,0]
print("unsorted list1 is", list1)
for j in range(len(list1)-1):
for i in range(len(list1)-1-j):
if list1[i]>list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/bubb3.py
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/bubb4.py
list1=[9,16,6,26,0]
print("unsorted list1 is", list1)
for j in range(len(list1)-1):
for i in range(len(list1)-1):
if list1[i]<list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print(list1)
else:
print(list1)
print( )
print("sorted list is",list1)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-2/pyyy/bubbdesc.py
unsorted list1 is [9, 16, 6, 26, 0]
[16, 9, 6, 26, 0]
[16, 9, 6, 26, 0]
[16, 9, 26, 6, 0]
[16, 9, 26, 6, 0]
[16, 9, 26, 6, 0]
[16, 26, 9, 6, 0]
[16, 26, 9, 6, 0]
[16, 26, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
[26, 16, 9, 6, 0]
Selection Sort:
list1=[5,3,7,1,9,6]
print(list1)
for i in range(len(list1)):
min_val=min(list1[i:])
min_ind=list1.index(min_val)
list1[i],list1[min_ind]=list1[min_ind],list1[i]
print(list1)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/selectasce.py
[5, 3, 7, 1, 9, 6]
[1, 3, 7, 5, 9, 6]
[1, 3, 7, 5, 9, 6]
[1, 3, 5, 7, 9, 6]
[1, 3, 5, 6, 9, 7]
[1, 3, 5, 6, 7, 9]
[1, 3, 5, 6, 7, 9]
#Write a python program to arrange the elements in descending order using selection sort:
list1=[5,3,7,1,9,6]
print(list1)
for i in range(len(list1)):
min_val=max(list1[i:])
min_ind=list1.index(min_val)
list1[i],list1[min_ind]=list1[min_ind],list1[i]
print(list1)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/selecdecs.py
[9, 7, 6, 5, 3, 1]
Note: If we want the elements to be sorted in descending order use max () method in place of min ().
Insertion Sort:
Insertion sort is not a fast sorting algorithm. It is useful only for small datasets.
It is a simple sorting algorithm that builds the final sorted list one item at a time.
Algorithm:
# Write a python program to arrange the elements in ascending order using insertion sort (with
functions)
def insertionsort(my_list):
current_element=my_list[index]
pos=index
my_list[pos]=my_list[pos-1]
pos=pos-1
my_list[pos]=current_element
print(list1)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/inserti.py
# Write a python program to arrange the elements in descending order using insertion sort (with
functions)
def insertionsort(my_list):
current_element=my_list[index]
pos=index
my_list[pos]=my_list[pos-1]
pos=pos-1
my_list[pos]=current_element
#list1=[3,5,1,0,10,2]
#insertionsort(list1)
#print(list1)
list1=[int(input())for i in range(num)]
insertionsort(list1)
print(list1)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/insertdesc.py
enter how many elements to be in list 5
8
1
4
10
2
[10, 8, 4, 2, 1]
Generally this merge sort works on the basis of divide and conquer algorithm. The three steps need to be
followed is divide, conquer and combine. We will be dividing the unsorted list into sub list until the single
element in a list is found.
Algorithm:
# Write a python program to arrange the elements in ascending order using Merge sort (with
functions)
def mergesort(list1):
if len(list1)>1:
mid=len(list1)//2
left_list=list1[:mid]
right_list=list1[mid:]
mergesort(left_list)
mergesort(right_list)
i=0
j=0
k=0
while i<len(left_list) and j<len(right_list):
if left_list[i]<right_list[j]:
list1[k]=left_list[i]
i=i+1
k=k+1
else:
list1[k]=right_list[j]
j=j+1
k=k+1
while i<len(left_list):
list1[k]=left_list[i]
i=i+1
k=k+1
while j<len(right_list):
list1[k]=right_list[j]
j=j+1
k=k+1
num=int(input("how many numbers in list1"))
list1=[int(input()) for x in range(num)]
mergesort(list1)
print("sorted list1",list1)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/merg.py
DATA STRUCTURES USING PYTHON Page 94
how many numbers in list15
5
9
10
1
66
sorted list1 [1, 5, 9, 10, 66]
Quick Sort:
Algorithm:
Note: Pivot element can be first, last, random elements or median of three values.
In the following program we are going to write 3 functions. The first function is to find pivot element and its
correct position. In second function we divide the list based on pivot element and sort the sub list and third
function (main fun) is to print input and output.
# Write a python program to arrange the elements in ascending order using Quick sort (with
functions)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/qucksort.py
[15, 25, 31, 44, 56, 93]
# Write a python program to arrange the elements in descending order using Quick sort (with
functions)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/qukdesc.py
Linked Lists:
Linked lists are one of the most commonly used data structures in any programming language. Linked Lists,
on the other hand, are different. Linked lists, do not store data at contiguous memory locations. For each
item in the memory location, linked list stores value of the item and the reference or pointer to the next item.
One pair of the linked list item and the reference to next item constitutes a node.
The program creates a linked list using data items input from the user and displays it.
Solution:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next
a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
Program Explanation
Stacks:
Stack works on the principle of “Last-in, first-out”. Also, the inbuilt functions in Python make the code
short and simple. To add an item to the top of the list, i.e., to push an item, we use append() function and to
pop out an element we use pop() function.
Output:
['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Iqbal
['Amar', 'Akbar', 'Anthony', 'Ram']
Ram
['Amar', 'Akbar', 'Anthony']
Queues:
Queue works on the principle of “First-in, first-out”. Time plays an important factor here. We saw that
during the implementation of stack we used append() and pop() function which was efficient and fast
because we inserted and popped elements from the end of the list, but in queue when insertion and pops are
made from the beginning of the list, it is slow. This occurs due to the properties of list, which is fast at the
end operations but slow at the beginning operations, as all other elements have to be shifted one by one. So,
we prefer the use of collections. Deque over list, which was specially designed to have fast appends and
pops from both the front and back end.
Output:
deque(['Ram', 'Tarun', 'Asif', 'John'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])
DATA STRUCTURES USING PYTHON Page 99
Ram
Tarun
deque(['Asif', 'John', 'Akbar', 'Birbal'])