SlideShare a Scribd company logo
K.ANGURAJU AP / CSE
List Basics * Copying Lists ,
Passing List to Functions * Returning
a List from function * Searching Lists
* Multidimensional Lists * Tuples *
Sets * Comparing Sets and Lists *
Dictionaries.
K.ANGURAJU AP / CSE
List Basics
CREATING A LIST / DEFINE LIST.
• A list contains items separated by commas and
enclosed with square bracket [ ] .
• List holds heterogeneous values
• List and arrays are same in python.
• values stored in list is accessed by using its index or its
value by slicing.
Syntax
List_name= [ value1, value2 …. Value n]
Example 1:
>>> List=[“ram”,31,54,12,47]
>>> list
[“ram”,31,54,12,47]
K.ANGURAJU AP / CSE
Example - 2:
colours = ['red', 'blue', 'green']
print colours[0] ## red
print colours[2] ## green
print len(colours) ## 3
K.ANGURAJU AP / CSE
Accessing values in lists
To access values in a list by using square
bracket [ ] , with the index 0,1,2 …. N, List is
accessed by using positive or negative
indexing.
positive indexing starting form 0,1,2,…. n
Negative indexing starting from -1, -2, -3
……-n
There are two methods available in list to access
the list data:
1.by using slices
2.by using indexes. K.ANGURAJU AP / CSE
By using indexes:
By using square bracket with index value to
access the list elements, here the index starts
from 0
Example:
list1=[‘ram’ , ‘ kumar’]
print ( list1[0])
Print( list2[1])
output:
[‘ram’]
[‘kumar’]
By using List slices:
We can also access the list element by
using slice method; here we access the
specific elements from the list.
Slice syntax:
list variable name[ starting index :
stop index – 1 ]
Example:
list1=[‘ram’ , ‘ kumar ’]
print( list1[ : ] )
Print(list1 [ 0 : ] )
output:
[ ‘ram’ , ‘ Kumar’ ]
[‘ram’ , ‘ Kumar’ ]
UPDATING A LIST:
Lists are mutable, which means the
elements in the list are updatable.
We can update it by using its index
position with square bracket.
Also to add a new entry within existing
entry.
Example
>>>List=[‘apple’, ’orange’, ’mango’, ‘pineapple’]
>>>print(list)
>>>List[0]=‘watermelon’
>>>Print(list)
>>>List[-1]=‘grapes’
>>>print(list)
Output:
[‘apple’, ’orange’, ’mango’, ‘pineapple’]
[‘watermelon’, ’orange’, ’mango’, ‘pineapple’]
[‘watermelon’, ’orange’, ’mango’, ‘grapes’]
Using slice operation we can update more than
one value in the list.
>>>list[1:3]=[‘strawberry’, ‘pomegranate’]
>>>print(list)
Output:
[ ‘Watermelon’ , ’strawberry’ , ‘pomegranate’ ,
’grapes’]
Deleting a list
Deletion is the process of deleting an
element from the existing list,
Deletion removes values from the list.
To delete the list element in two ways.
• By using del keyword
• By using pop() function.
By using del keyword
Examples
>>>List=[‘watermelon’, ’orange’, ’mango’,
‘pineapple’]
del list[0]
print(list)
Output:
[’orange’, ’mango’, ‘pineapple’]
To delete by using slice :
List=[’orange’, ’mango’, ‘pineapple’]
del list[1:3]
print(list)
Output:
[‘orange’]
By using pop() method
list . pop(index)
pop () is one of the list method ,it Removes and returns those
element at the given index
List=[1,2,3,4,5]
List.pop(4) #index
5
Print(list)
[1,2,3,4]
List is a sequence type
List and string’s are sequence type in
python.
A string is a sequence of character
While List also having sequence of
elements.
those sequence to be accessed by for
loop and set of basic function.
Example: list functions
>>> a=[1,2,3,4,5]
>>> len(a)
5
>>> max(a)
5
>>> min(a)
1
>>> sum(a)
15
For loop - Traverse the element from left to
right
<, >, <=, >=, = - Used to compare two list
+ - s1+s2 - concatenate two sequence
Comparing List
List are compared by using (<, >, <=, >=, = )
Operator’s
Example:
A=[1,2,3]
B=[1,2,3]
>>>A==B
True
>>>A!=B
False
Traverse Elements in a for Loop
A loop is a block of code that repeats
itself until a certain condition satisfied. Here
we use the simple for loop to print all the
content with in the text file.
Example:
Ice_cream=[‘vanilla’, ’chocolate’,’ strawberry’]
for i in ice_cream :
print(i)
OUTPUT:
vanilla
chocolate
strawberry
List Loop (using range function)
The range() function returns sequence of
integers between the given start integers to
the stop integers
Syntax:
range(start, stop, step)
example
A=[10,20,30,40]
for i in range(0,4,1):
print(a[i])
List operators
List having more operation like string ( ‘
+ ‘ and ‘ * ‘ ), that is concatenation, in and not
in
Following basic operation performed in list:
Concadenation (+)
Repetation (*)
Membership (in)
K.ANGURAJU AP / CSE
Expression Results Description
[1,2,3,4]+[5,6] [1,2,3,4,5,6]
Concatenation is the process of
combine two list elements (+)
[‘hi’]*2 [‘hi’,’hi’]
To repeat the list elements in
specified number of time
(Repetition)
2 in [1,2,3] True
Membership – To find specified
elements is in the list or not
K.ANGURAJU AP / CSE
List methods
• Python has a number of built-in data
structures in list.
• These methods are used as a way to organize
and store data in the list.
• Methods that are available in list are given
below
• They are accessed as list.method()
K.ANGURAJU AP / CSE
Methods Description
Append()
Add an element to the end of the list
Extend()
Add all the element of the list to the another list
Insert()
Insert an element at the defined index
Remove()
Removes an element from the list
Pop()
Removes and returns an element at the given
index
Clear()
Removes all the element from the list
Index()
Returns the list of the matched element
Count()
Returns the number of times the element present
in the list
Sort()
Sort the element in ascending order
Reverse()
Reverse the order of the element in the list
Copy()
Copy the elements in the list
K.ANGURAJU AP / CSE
Append()
list.append(element )
append() is one of the list method , It will add a single element to
the end of the list.
Example:
List=[1,2,3,4,5]
List. append(6)
Print(list)
Output:
[1,2,3,4,5,6]
Insert()
list. insert(index, element)
insert () is one of the list method ,it inserts the element at the
specified index.
Example:
List=[1,2,3,4,5]
List. insert(4,7)
Print(list)
Output:
[1,2,3,4,7,5] K.ANGURAJU AP / CSE
Extend() – list1 . extend(list2)
Extend () is one of the list method ,it Add all the element of
the one list to the another list.
aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'mani'];
aList.extend(bList)
print ("Extended List : ", aList )
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'mani']
POP()
list . pop(index)
pop () is one of the list method ,it Removes and returns those
element at the given index
List=[1,2,3,4,5]
List.pop(4) #index
5
Print(list)
[1,2,3,4]
K.ANGURAJU AP / CSE
Index()- list . Index(element)
index () is one of the list method ,it Returns
the index position of the matched element.
List=[1,2,3,4,5]
List.index(4)
Output: 3 #index
COPY()- list2 = list1.copy()
copy () is one of the list method ,it Copy the
elements from the one list and assign into a new
list.
List1=[1,2,3,4,5]
list2=List1.copy()
Print(list2)
Output: [1,2,3,4,5]
K.ANGURAJU AP / CSE
Reverse()-
reverse () is one of the list method ,it Reverse
the order of the element in the list
List=[1,2,3,4,5]
list.reverse()
Print(list)
Output: [5,4,3,2,1]
Count()-
count () is one of the list method ,it Returns
the number of times the element present in the list.
List=[1,2,3,4,5]
List.count(5)
Print(list)
Output: 1 K.ANGURAJU AP / CSE
Sort()- sort () is one of the list method ,it Sort
the element in ascending order
List=[4,7,2,3]
List.sort()
Print(list)
Output: [2,3,4,7]
Clear()- clear() is one of the list method ,it
Removes all the element from the list
List=[1,2,3,4]
List.clear()
Print(list)
Output: none
K.ANGURAJU AP / CSE
Remove() - list.remove(element)
remove () is one of the list method ,it
Removes the specified element from the list
List=[1,2,3,4,5]
List.remove(4) #element
Print(list)
Output: [1,2,3,5]
K.ANGURAJU AP / CSE
Copying List
Copying the data in one list to another list You can copy individual
elements from the source list to target list.
By using assignment operator to copy the one list element to another
list.
Syntax:
Destination list =Source list
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> id(a)
2209400268544
>>> id(b)
2209392450432
>>> b=a
>>> id(b)
2209400268544
>>> b
[1, 2, 3]
>>>
LIST LOOP
we can possible to apply looping statements into
list , to access the list elements
A loop is a block of code that repeats itself until a
certain condition satisfied.
It avoid the complexity of the program.
Example program:
Ice_cream=[‘vanilla’, ’chocolate’,’ strawberry’]
for i in ice_cream :
print(i)
OUTPUT:
vanilla
chocolate
strawberry
Passing Lists to Function
• Passing list as a function arguments is called
as list parameter.
• Actually it passes a reference to the list, not a
copy of the list.
• Since list are mutable changes made in
parameter it will change the actual argument.
Example:
>>>def display(temp): #function definition
print(temp)
>>> x=[10,20,30,40,50]
>>> display(x) # function call
Output: [10, 20, 30, 40, 50]
y=[10,20,’regan’,’arun’,30.5]
display(y)
Output: [10,20,’regan’,’arun’,30.5]
Returning a List from function
The function call send list of data to
function definition.
also the function definition return the
resultant list to corresponding function call is
called returning a list from a function
Searching List
Searching is the process of looking for a
specific element in a list.
In this we search the individual element
from the list by using indexes.
There are two methods to search the
elements.
1.Linear Search
2.Binary Search
#Linear Search program
a=[0,0,0,0,0,0,0,0,0,0]
s=0
n=int (input("enter the number of element:"))
print("enter the",n," numbers")
for i in range(0,n,1):
a[i]=int (input())
s_element=int ( input("enter the searching element:"))
for i in range(0,len(a),1):
while(a[i]==s_element):
print("the element is found:", a[i])
s=1
break
If(s==0):
print(“The element is not found”)
Binary Search Program:
a=[2,3,5,6,8,56,34]
a.sort()
print("The sorted list elements are",a)
s=int(input("enter the searching element"))
lower=0
upper=6
while(lower<=upper):
mid=int((lower+upper)/2)
if(s>a[mid]):
lower=mid+1
elif(s<a[mid]):
upper=mid-1
elif(s==a[mid]):
print("the element is found")
break
else:
print("element is not found")
0 1 2 3 4 5 6
a=[ 2,3,5,6,8,34,56] s=34
low=4
Upp=6
While(low<=upp) 4<=6 T
Mid=low+upp/2 4+6/2 5
If(s= = a[mid]) (34= = a[5])
(34==34) T
Write a python program to sort the given list
elements by using selection sort
A=[0,0,0,0,0,0,0,0]
n=int (input("enter the n value"))
print("Enter the list element")
for i in range(0,n,1):
A[i]=int (input())
print(A)
for i in range(0, len(A) ,1):
fillslot = i
for j in range(i+1, len(A),1):
minpos=j
if (A[fillslot] >= A[minpos]):
temp =A[fillslot]
A[fillslot]=A[minpos]
A[minpos]=temp
print("sorted list elements are", A)
Output:
enter the n value5 Enter the list element
19 2 3 5 6
[19, 2, 3, 5, 6, 0, 0, 0]
Sorted list elements are [0, 0, 0, 2, 3, 5, 6, 19]
Multidimensional list
Data in a table or a matrix can be stored in a
two dimensional list.
The value in a two dimensional list can be
accessed through a row and column indexes.
Here the data stored in row wise as well as data
accessed using row and column indexes.
Example:
A=[ [ 1,2],
[2,3] ]
TUPLE
• Tuple contains items separated by commas and
enclosed with parenthesis().
• Values cannot be edit or update and insert a new
value in Tuple.
• The values in tuples can be stored any type.
• Tuples are immutable.
Example:
>>>tuple=(10,20,30,’dhoni’,’K’,)
>>>print(tuple)
(10,20,30,’dhoni’,’K’,)
Tuple elements are accessed by using it’s
indexes with [] ,also accessed using slices
Print values by using index:
>>>tuples=(‘a’, ’b’, ’c’, ’d’)
>>>print(tuples[0])
output: a
Print values by using slicing:
>>> print(tuples[1:3])
output: (‘b’, ’c’)
If we change values of a tuple it shows:
tuples[0]=‘z’
output: Error: object does not support item
assignment
TUPLE ASSIGNMENT:
To define a tuple we should assign more than
one values or one element with comma.
>>>t1=(‘a’)
>>>print(t1)
>>>a
Type(t1)
<class 'str'>
>>>t1=(‘a,’)
>>>print(t1)
>>>a
Type(t1)
<class ‘tuple'>
Multiple tuple assignment:
(a, b, c, d) = (1, 2, 3,4)
>>> print(a, b, c, d)
Output: 1 2 3 4
Assign tuple values into a variable by using index:
>>>m=(‘hai’, ‘hello’)
>>>x=m[0]
>>>y=m[1]
>>>x
‘hai’
>>>y
‘hello’
Assign tuple values into multiple variable:
>>>m=(‘hai’, ‘hello’)
>>>(x,y)=m
>>>x
‘hai’
>>>y
‘hello’
Swapping
To swap two number we need
temporary variable in normal swapping .
For example, to swap a and b
>>>a=10; b=20
>>>temp = a
>>>a = b
>>>b = temp
The tuple assignment allows us to swap
the values of two variables in a single
statement.
>>>(a, b) = (b, a)
Tuple as return values
• A normal function can only return one value, but
the effect of tuple functions returning multiple
values.
• For example, if you want to divide two integers
and compute the quotient and remainder, it is
inefficient to compute x/y and then x%y.
• The built-in function divmod takes two
arguments and returns a tuple of two values, the
quotient and remainder.
Example:
>>> t= divmod(7,3)
>>>print t
Output: (2,1)
(Or)
>>>quot, rem=divmod(7,3)
>>>print quot
Output: 2
>>>print rem
Output: 1
Tuple predefined function
• len() – provide number of item present in the tuple
Example:
a=(1,2,3,4)
print(len(a))
Output:
4
• min() – this function return minimum number in a
tuple
Example:
a=(1,2,3,4)
print(min(a))
Output:
1
• max() - this function return maximum number in a
tuple
Example:
a=(1,2,3,4)
print(max(a))
Output:
4
• sum() – this function sums the individual item
Example:
a=(1,2,3,4)
print(sum(a))
Output:
10
• Count() - it returns number of time repeated count of specified
element.
Example:
a=(1,2,3,4)
print(a.count(4))
Output:
1
• cmp() – This check the given tuple are same or not, if both same it
return zero(0), if the first tuple big then return 1, Otherwise return
-1
Example:
t1=(1,2,3,4)
t2=(1,2,3,4)
print(cmp(t1,t2)
Output:
0
SETS IN PYHTON
Lists and tuples are standard Python
data types that store values in a sequence.
Sets are another standard Python data
type that also store values.
The major difference is that sets, unlike
lists or tuples, cannot have multiple
occurrences of the same element
And store unordered values.
Because sets cannot have multiple
occurrences of the same element,
it makes sets highly useful to efficiently
remove duplicate values from a list or tuple
and to perform common math
operations like unions and intersections.
Initialize a Set
you can initialize an empty set by using set().
Example:
emptySet = set()
To initialize a set with values, you can pass in a
list to set().
>>> dataEngineer = set(['Python', 'Java', 'Scala',
'Git', 'SQL', 'Hadoop'])
>>> dataEngineer
{'Hadoop', 'Scala', 'Java', 'Git', 'SQL', 'Python'}
If you look at the output of dataEngineer
variables above, notice that the values in the
set are not in the order added in. This is
because sets are unordered.
Sets containing values can also be
initialized by using curly braces.
>>> dataEngineer = {'Python', 'Java', 'Scala', 'Git',
'SQL', 'Hadoop'}
>>> dataScientist = {'Python', 'R', 'SQL', 'Git',
'Tableau', 'SAS'}
Output:
>>> dataEngineer
{'Scala', 'SQL', 'Java', 'Git', 'Hadoop', 'Python'}
Difference between set and list
List :
The list is a data type available in Python
which can be written as a list of comma-
separated values (items) between square
brackets.
List are mutable .i.e it can be converted
into another data type and can store any data
element in it.
List can store any type of element.
SETS:
Sets are an unordered collection of
elements or unintended collection of items In
python.
Here the order in which the elements
are added into the set is not fixed, it can
change frequently.
It is defined under curly braces{}
Sets are mutable, however, only
immutable objects can be stored in it.
Dictionaries
• Python’s dictionaries are kind of hash-table type
• They work like associative arrays or hashes found
in Perl and consist of key-value pairs.
• A dictionary key can be almost any Python type,
but are usually numbers or strings.
• Dictionaries are enclosed by curly braces ({ }) and
values can be assigned and accessed using
square braces ([]).
a = {‘name’: ‘john’,‘code’:6734, ‘dept’: ‘sales’}
print (a) # Prints complete dictionary
print (a.keys()) # Prints all the keys
print (a.values()) # Prints all the values
This produces the following result-
{‘name’: ‘john’, ‘code’:6734, ‘dept’: ‘sales’}
[‘dept’, ‘code’, ‘name’]
[‘sales’, 6734, ‘john’]
Accessing values in a dictionary
To access dictionary elements, you can use the
familiar square brackets along with the key to
obtain its value.
There are two methods available in dictionary
to access the dictionary data:
By using slices
By using keys.
By using Keys:
By using square bracket with Key value to
access the dictionary elements
Example:
friends = { “name” : “ram” , “age” : 18 ,
“address”: “trichy” }
print ( friends [ “name” ])
print ( friends [ “age” ])
print ( friends [ “address” ])
Output:
{ “name” : “ram” }
{ “age” : 18 }
{ “address”: “trichy” }
Updating a dictionary:
Dictionary is also mutable,
which means the elements in the dictionary
are updatable.
We can update it by using its key with square
bracket.
Also to add a new entry within existing entry.
We can update a dictionary by adding a new
entry or modifying an existing entry, or
deleting an existing entry.
Updating a Dictionary:
Example:
friends = { “name” : “ram” , “age” : 18 ,
“address”: “trichy” }
friends [ “name” ] = “siva”
friends [ “age” ] = 19
friends [ “address” ] = “namakkal”
Output:
{“name” : “siva” , “age” : 19 , “address”:
“namakkal” }
Adding new entry
To add a new entry within the existing
dictionary by using the its index position to
assign dictionary element .
Example:
friends = { “name” : “ram” , “age” : 18 ,
“address”: “trichy” }
friends [ 3 ] = { “mobile number” : 0123456789 }
print ( friends )
Output:
{ “name” : “ram” , “age” : 18 , “address”:
“trichy” , { “mobile number” : 0123456789 }}
Deleting element in a dictionary
Deletion is the process of deleting an element
from the existing dictionary; Deletion removes
values from the dictionary. To delete the
dictionary element in two ways.
By using del keyword
By using pop() function.
By using del keyword
Example:
friends = { “name” : “ram” , “age” : 18 ,
“address”: “trichy” }
del friends[0]
print(friends)
Output:
{ “age” : 18 , “address”: “trichy” }
To delete by using slice :
Example:
friends = { “name” : “ram” , “age” : 18 ,
“address”: “trichy” }
del friends[ 0 : 2]
print(friends)
Output:
{ “address”: “trichy” }
By using pop() method
Example:
friends = { “name” : “ram” , “age” : 18 ,
“address”: “trichy” }
friends . pop(“age”)
print(frieds)
Output:
{ “name” : “ram” , “address”: “trichy” }

More Related Content

Similar to UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON (20)

PPTX
Chapter 15 Lists
Praveen M Jigajinni
 
PPTX
Python list
ArchanaBhumkar
 
PPTX
Module-2.pptx
GaganRaj28
 
PPTX
Python list concept
DrJSaiGeetha
 
PDF
Python lists &amp; sets
Aswini Dharmaraj
 
PDF
List in Python Using Back Developers in Using More Use.
SravaniSravani53
 
PPTX
Unit 4 python -list methods
narmadhakin
 
PPTX
List in Python
Siddique Ibrahim
 
PDF
List,tuple,dictionary
nitamhaske
 
PPTX
Python for Beginners(v3)
Panimalar Engineering College
 
PPTX
updated_list.pptx
Koteswari Kasireddy
 
PDF
Module III.pdf
R.K.College of engg & Tech
 
PPTX
listtupledictionary-2001okdhfuihcasbdjj02082611.pptx
meganathan162007
 
PPTX
list in python and traversal of list.pptx
urvashipundir04
 
PPTX
listppt.pptx h4wtgesvzdfvgsrbyhrrtgsvefcdef
rajpalyadav13052024
 
PPTX
Python lists
nuripatidar
 
PDF
Data type list_methods_in_python
deepalishinkar1
 
PDF
Unit 1-Part-4-Lists, tuples and dictionaries.pdf
Harsha Patil
 
PPTX
Lists.pptx
Yagna15
 
Chapter 15 Lists
Praveen M Jigajinni
 
Python list
ArchanaBhumkar
 
Module-2.pptx
GaganRaj28
 
Python list concept
DrJSaiGeetha
 
Python lists &amp; sets
Aswini Dharmaraj
 
List in Python Using Back Developers in Using More Use.
SravaniSravani53
 
Unit 4 python -list methods
narmadhakin
 
List in Python
Siddique Ibrahim
 
List,tuple,dictionary
nitamhaske
 
Python for Beginners(v3)
Panimalar Engineering College
 
updated_list.pptx
Koteswari Kasireddy
 
listtupledictionary-2001okdhfuihcasbdjj02082611.pptx
meganathan162007
 
list in python and traversal of list.pptx
urvashipundir04
 
listppt.pptx h4wtgesvzdfvgsrbyhrrtgsvefcdef
rajpalyadav13052024
 
Python lists
nuripatidar
 
Data type list_methods_in_python
deepalishinkar1
 
Unit 1-Part-4-Lists, tuples and dictionaries.pdf
Harsha Patil
 
Lists.pptx
Yagna15
 

Recently uploaded (20)

PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PPTX
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PDF
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Ad

UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON

  • 2. List Basics * Copying Lists , Passing List to Functions * Returning a List from function * Searching Lists * Multidimensional Lists * Tuples * Sets * Comparing Sets and Lists * Dictionaries. K.ANGURAJU AP / CSE
  • 3. List Basics CREATING A LIST / DEFINE LIST. • A list contains items separated by commas and enclosed with square bracket [ ] . • List holds heterogeneous values • List and arrays are same in python. • values stored in list is accessed by using its index or its value by slicing. Syntax List_name= [ value1, value2 …. Value n] Example 1: >>> List=[“ram”,31,54,12,47] >>> list [“ram”,31,54,12,47] K.ANGURAJU AP / CSE
  • 4. Example - 2: colours = ['red', 'blue', 'green'] print colours[0] ## red print colours[2] ## green print len(colours) ## 3 K.ANGURAJU AP / CSE
  • 5. Accessing values in lists To access values in a list by using square bracket [ ] , with the index 0,1,2 …. N, List is accessed by using positive or negative indexing. positive indexing starting form 0,1,2,…. n Negative indexing starting from -1, -2, -3 ……-n There are two methods available in list to access the list data: 1.by using slices 2.by using indexes. K.ANGURAJU AP / CSE
  • 6. By using indexes: By using square bracket with index value to access the list elements, here the index starts from 0 Example: list1=[‘ram’ , ‘ kumar’] print ( list1[0]) Print( list2[1]) output: [‘ram’] [‘kumar’]
  • 7. By using List slices: We can also access the list element by using slice method; here we access the specific elements from the list. Slice syntax: list variable name[ starting index : stop index – 1 ]
  • 8. Example: list1=[‘ram’ , ‘ kumar ’] print( list1[ : ] ) Print(list1 [ 0 : ] ) output: [ ‘ram’ , ‘ Kumar’ ] [‘ram’ , ‘ Kumar’ ]
  • 9. UPDATING A LIST: Lists are mutable, which means the elements in the list are updatable. We can update it by using its index position with square bracket. Also to add a new entry within existing entry.
  • 10. Example >>>List=[‘apple’, ’orange’, ’mango’, ‘pineapple’] >>>print(list) >>>List[0]=‘watermelon’ >>>Print(list) >>>List[-1]=‘grapes’ >>>print(list) Output: [‘apple’, ’orange’, ’mango’, ‘pineapple’] [‘watermelon’, ’orange’, ’mango’, ‘pineapple’] [‘watermelon’, ’orange’, ’mango’, ‘grapes’]
  • 11. Using slice operation we can update more than one value in the list. >>>list[1:3]=[‘strawberry’, ‘pomegranate’] >>>print(list) Output: [ ‘Watermelon’ , ’strawberry’ , ‘pomegranate’ , ’grapes’]
  • 12. Deleting a list Deletion is the process of deleting an element from the existing list, Deletion removes values from the list. To delete the list element in two ways. • By using del keyword • By using pop() function.
  • 13. By using del keyword Examples >>>List=[‘watermelon’, ’orange’, ’mango’, ‘pineapple’] del list[0] print(list) Output: [’orange’, ’mango’, ‘pineapple’]
  • 14. To delete by using slice : List=[’orange’, ’mango’, ‘pineapple’] del list[1:3] print(list) Output: [‘orange’]
  • 15. By using pop() method list . pop(index) pop () is one of the list method ,it Removes and returns those element at the given index List=[1,2,3,4,5] List.pop(4) #index 5 Print(list) [1,2,3,4]
  • 16. List is a sequence type List and string’s are sequence type in python. A string is a sequence of character While List also having sequence of elements. those sequence to be accessed by for loop and set of basic function.
  • 17. Example: list functions >>> a=[1,2,3,4,5] >>> len(a) 5 >>> max(a) 5 >>> min(a) 1 >>> sum(a) 15
  • 18. For loop - Traverse the element from left to right <, >, <=, >=, = - Used to compare two list + - s1+s2 - concatenate two sequence
  • 19. Comparing List List are compared by using (<, >, <=, >=, = ) Operator’s Example: A=[1,2,3] B=[1,2,3] >>>A==B True >>>A!=B False
  • 20. Traverse Elements in a for Loop A loop is a block of code that repeats itself until a certain condition satisfied. Here we use the simple for loop to print all the content with in the text file. Example: Ice_cream=[‘vanilla’, ’chocolate’,’ strawberry’] for i in ice_cream : print(i) OUTPUT: vanilla chocolate strawberry
  • 21. List Loop (using range function) The range() function returns sequence of integers between the given start integers to the stop integers Syntax: range(start, stop, step) example A=[10,20,30,40] for i in range(0,4,1): print(a[i])
  • 22. List operators List having more operation like string ( ‘ + ‘ and ‘ * ‘ ), that is concatenation, in and not in Following basic operation performed in list: Concadenation (+) Repetation (*) Membership (in) K.ANGURAJU AP / CSE
  • 23. Expression Results Description [1,2,3,4]+[5,6] [1,2,3,4,5,6] Concatenation is the process of combine two list elements (+) [‘hi’]*2 [‘hi’,’hi’] To repeat the list elements in specified number of time (Repetition) 2 in [1,2,3] True Membership – To find specified elements is in the list or not K.ANGURAJU AP / CSE
  • 24. List methods • Python has a number of built-in data structures in list. • These methods are used as a way to organize and store data in the list. • Methods that are available in list are given below • They are accessed as list.method() K.ANGURAJU AP / CSE
  • 25. Methods Description Append() Add an element to the end of the list Extend() Add all the element of the list to the another list Insert() Insert an element at the defined index Remove() Removes an element from the list Pop() Removes and returns an element at the given index Clear() Removes all the element from the list Index() Returns the list of the matched element Count() Returns the number of times the element present in the list Sort() Sort the element in ascending order Reverse() Reverse the order of the element in the list Copy() Copy the elements in the list K.ANGURAJU AP / CSE
  • 26. Append() list.append(element ) append() is one of the list method , It will add a single element to the end of the list. Example: List=[1,2,3,4,5] List. append(6) Print(list) Output: [1,2,3,4,5,6] Insert() list. insert(index, element) insert () is one of the list method ,it inserts the element at the specified index. Example: List=[1,2,3,4,5] List. insert(4,7) Print(list) Output: [1,2,3,4,7,5] K.ANGURAJU AP / CSE
  • 27. Extend() – list1 . extend(list2) Extend () is one of the list method ,it Add all the element of the one list to the another list. aList = [123, 'xyz', 'zara', 'abc', 123]; bList = [2009, 'mani']; aList.extend(bList) print ("Extended List : ", aList ) Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'mani'] POP() list . pop(index) pop () is one of the list method ,it Removes and returns those element at the given index List=[1,2,3,4,5] List.pop(4) #index 5 Print(list) [1,2,3,4] K.ANGURAJU AP / CSE
  • 28. Index()- list . Index(element) index () is one of the list method ,it Returns the index position of the matched element. List=[1,2,3,4,5] List.index(4) Output: 3 #index COPY()- list2 = list1.copy() copy () is one of the list method ,it Copy the elements from the one list and assign into a new list. List1=[1,2,3,4,5] list2=List1.copy() Print(list2) Output: [1,2,3,4,5] K.ANGURAJU AP / CSE
  • 29. Reverse()- reverse () is one of the list method ,it Reverse the order of the element in the list List=[1,2,3,4,5] list.reverse() Print(list) Output: [5,4,3,2,1] Count()- count () is one of the list method ,it Returns the number of times the element present in the list. List=[1,2,3,4,5] List.count(5) Print(list) Output: 1 K.ANGURAJU AP / CSE
  • 30. Sort()- sort () is one of the list method ,it Sort the element in ascending order List=[4,7,2,3] List.sort() Print(list) Output: [2,3,4,7] Clear()- clear() is one of the list method ,it Removes all the element from the list List=[1,2,3,4] List.clear() Print(list) Output: none K.ANGURAJU AP / CSE
  • 31. Remove() - list.remove(element) remove () is one of the list method ,it Removes the specified element from the list List=[1,2,3,4,5] List.remove(4) #element Print(list) Output: [1,2,3,5] K.ANGURAJU AP / CSE
  • 32. Copying List Copying the data in one list to another list You can copy individual elements from the source list to target list. By using assignment operator to copy the one list element to another list. Syntax: Destination list =Source list
  • 33. >>> a=[1,2,3] >>> b=[4,5,6] >>> id(a) 2209400268544 >>> id(b) 2209392450432 >>> b=a >>> id(b) 2209400268544 >>> b [1, 2, 3] >>>
  • 34. LIST LOOP we can possible to apply looping statements into list , to access the list elements A loop is a block of code that repeats itself until a certain condition satisfied. It avoid the complexity of the program. Example program: Ice_cream=[‘vanilla’, ’chocolate’,’ strawberry’] for i in ice_cream : print(i) OUTPUT: vanilla chocolate strawberry
  • 35. Passing Lists to Function • Passing list as a function arguments is called as list parameter. • Actually it passes a reference to the list, not a copy of the list. • Since list are mutable changes made in parameter it will change the actual argument.
  • 36. Example: >>>def display(temp): #function definition print(temp) >>> x=[10,20,30,40,50] >>> display(x) # function call Output: [10, 20, 30, 40, 50] y=[10,20,’regan’,’arun’,30.5] display(y) Output: [10,20,’regan’,’arun’,30.5]
  • 37. Returning a List from function The function call send list of data to function definition. also the function definition return the resultant list to corresponding function call is called returning a list from a function
  • 38. Searching List Searching is the process of looking for a specific element in a list. In this we search the individual element from the list by using indexes. There are two methods to search the elements. 1.Linear Search 2.Binary Search
  • 39. #Linear Search program a=[0,0,0,0,0,0,0,0,0,0] s=0 n=int (input("enter the number of element:")) print("enter the",n," numbers") for i in range(0,n,1): a[i]=int (input()) s_element=int ( input("enter the searching element:")) for i in range(0,len(a),1): while(a[i]==s_element): print("the element is found:", a[i]) s=1 break If(s==0): print(“The element is not found”)
  • 40. Binary Search Program: a=[2,3,5,6,8,56,34] a.sort() print("The sorted list elements are",a) s=int(input("enter the searching element")) lower=0 upper=6
  • 42. 0 1 2 3 4 5 6 a=[ 2,3,5,6,8,34,56] s=34 low=4 Upp=6 While(low<=upp) 4<=6 T Mid=low+upp/2 4+6/2 5 If(s= = a[mid]) (34= = a[5]) (34==34) T
  • 43. Write a python program to sort the given list elements by using selection sort A=[0,0,0,0,0,0,0,0] n=int (input("enter the n value")) print("Enter the list element") for i in range(0,n,1): A[i]=int (input()) print(A)
  • 44. for i in range(0, len(A) ,1): fillslot = i for j in range(i+1, len(A),1): minpos=j if (A[fillslot] >= A[minpos]): temp =A[fillslot] A[fillslot]=A[minpos] A[minpos]=temp print("sorted list elements are", A)
  • 45. Output: enter the n value5 Enter the list element 19 2 3 5 6 [19, 2, 3, 5, 6, 0, 0, 0] Sorted list elements are [0, 0, 0, 2, 3, 5, 6, 19]
  • 46. Multidimensional list Data in a table or a matrix can be stored in a two dimensional list. The value in a two dimensional list can be accessed through a row and column indexes. Here the data stored in row wise as well as data accessed using row and column indexes. Example: A=[ [ 1,2], [2,3] ]
  • 47. TUPLE • Tuple contains items separated by commas and enclosed with parenthesis(). • Values cannot be edit or update and insert a new value in Tuple. • The values in tuples can be stored any type. • Tuples are immutable. Example: >>>tuple=(10,20,30,’dhoni’,’K’,) >>>print(tuple) (10,20,30,’dhoni’,’K’,)
  • 48. Tuple elements are accessed by using it’s indexes with [] ,also accessed using slices Print values by using index: >>>tuples=(‘a’, ’b’, ’c’, ’d’) >>>print(tuples[0]) output: a Print values by using slicing: >>> print(tuples[1:3]) output: (‘b’, ’c’) If we change values of a tuple it shows: tuples[0]=‘z’ output: Error: object does not support item assignment
  • 49. TUPLE ASSIGNMENT: To define a tuple we should assign more than one values or one element with comma. >>>t1=(‘a’) >>>print(t1) >>>a Type(t1) <class 'str'> >>>t1=(‘a,’) >>>print(t1) >>>a Type(t1) <class ‘tuple'>
  • 50. Multiple tuple assignment: (a, b, c, d) = (1, 2, 3,4) >>> print(a, b, c, d) Output: 1 2 3 4
  • 51. Assign tuple values into a variable by using index: >>>m=(‘hai’, ‘hello’) >>>x=m[0] >>>y=m[1] >>>x ‘hai’ >>>y ‘hello’ Assign tuple values into multiple variable: >>>m=(‘hai’, ‘hello’) >>>(x,y)=m >>>x ‘hai’ >>>y ‘hello’
  • 52. Swapping To swap two number we need temporary variable in normal swapping . For example, to swap a and b >>>a=10; b=20 >>>temp = a >>>a = b >>>b = temp The tuple assignment allows us to swap the values of two variables in a single statement. >>>(a, b) = (b, a)
  • 53. Tuple as return values • A normal function can only return one value, but the effect of tuple functions returning multiple values. • For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x/y and then x%y. • The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder.
  • 54. Example: >>> t= divmod(7,3) >>>print t Output: (2,1) (Or) >>>quot, rem=divmod(7,3) >>>print quot Output: 2 >>>print rem Output: 1
  • 55. Tuple predefined function • len() – provide number of item present in the tuple Example: a=(1,2,3,4) print(len(a)) Output: 4 • min() – this function return minimum number in a tuple Example: a=(1,2,3,4) print(min(a)) Output: 1
  • 56. • max() - this function return maximum number in a tuple Example: a=(1,2,3,4) print(max(a)) Output: 4 • sum() – this function sums the individual item Example: a=(1,2,3,4) print(sum(a)) Output: 10
  • 57. • Count() - it returns number of time repeated count of specified element. Example: a=(1,2,3,4) print(a.count(4)) Output: 1 • cmp() – This check the given tuple are same or not, if both same it return zero(0), if the first tuple big then return 1, Otherwise return -1 Example: t1=(1,2,3,4) t2=(1,2,3,4) print(cmp(t1,t2) Output: 0
  • 58. SETS IN PYHTON Lists and tuples are standard Python data types that store values in a sequence. Sets are another standard Python data type that also store values. The major difference is that sets, unlike lists or tuples, cannot have multiple occurrences of the same element And store unordered values.
  • 59. Because sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections.
  • 60. Initialize a Set you can initialize an empty set by using set(). Example: emptySet = set()
  • 61. To initialize a set with values, you can pass in a list to set(). >>> dataEngineer = set(['Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop']) >>> dataEngineer {'Hadoop', 'Scala', 'Java', 'Git', 'SQL', 'Python'} If you look at the output of dataEngineer variables above, notice that the values in the set are not in the order added in. This is because sets are unordered.
  • 62. Sets containing values can also be initialized by using curly braces. >>> dataEngineer = {'Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop'} >>> dataScientist = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'} Output: >>> dataEngineer {'Scala', 'SQL', 'Java', 'Git', 'Hadoop', 'Python'}
  • 63. Difference between set and list List : The list is a data type available in Python which can be written as a list of comma- separated values (items) between square brackets. List are mutable .i.e it can be converted into another data type and can store any data element in it. List can store any type of element.
  • 64. SETS: Sets are an unordered collection of elements or unintended collection of items In python. Here the order in which the elements are added into the set is not fixed, it can change frequently. It is defined under curly braces{} Sets are mutable, however, only immutable objects can be stored in it.
  • 65. Dictionaries • Python’s dictionaries are kind of hash-table type • They work like associative arrays or hashes found in Perl and consist of key-value pairs. • A dictionary key can be almost any Python type, but are usually numbers or strings. • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
  • 66. a = {‘name’: ‘john’,‘code’:6734, ‘dept’: ‘sales’} print (a) # Prints complete dictionary print (a.keys()) # Prints all the keys print (a.values()) # Prints all the values This produces the following result- {‘name’: ‘john’, ‘code’:6734, ‘dept’: ‘sales’} [‘dept’, ‘code’, ‘name’] [‘sales’, 6734, ‘john’]
  • 67. Accessing values in a dictionary To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. There are two methods available in dictionary to access the dictionary data: By using slices By using keys. By using Keys: By using square bracket with Key value to access the dictionary elements
  • 68. Example: friends = { “name” : “ram” , “age” : 18 , “address”: “trichy” } print ( friends [ “name” ]) print ( friends [ “age” ]) print ( friends [ “address” ]) Output: { “name” : “ram” } { “age” : 18 } { “address”: “trichy” }
  • 69. Updating a dictionary: Dictionary is also mutable, which means the elements in the dictionary are updatable. We can update it by using its key with square bracket. Also to add a new entry within existing entry. We can update a dictionary by adding a new entry or modifying an existing entry, or deleting an existing entry.
  • 70. Updating a Dictionary: Example: friends = { “name” : “ram” , “age” : 18 , “address”: “trichy” } friends [ “name” ] = “siva” friends [ “age” ] = 19 friends [ “address” ] = “namakkal” Output: {“name” : “siva” , “age” : 19 , “address”: “namakkal” }
  • 71. Adding new entry To add a new entry within the existing dictionary by using the its index position to assign dictionary element . Example: friends = { “name” : “ram” , “age” : 18 , “address”: “trichy” } friends [ 3 ] = { “mobile number” : 0123456789 } print ( friends ) Output: { “name” : “ram” , “age” : 18 , “address”: “trichy” , { “mobile number” : 0123456789 }}
  • 72. Deleting element in a dictionary Deletion is the process of deleting an element from the existing dictionary; Deletion removes values from the dictionary. To delete the dictionary element in two ways. By using del keyword By using pop() function. By using del keyword Example: friends = { “name” : “ram” , “age” : 18 , “address”: “trichy” } del friends[0]
  • 73. print(friends) Output: { “age” : 18 , “address”: “trichy” } To delete by using slice : Example: friends = { “name” : “ram” , “age” : 18 , “address”: “trichy” } del friends[ 0 : 2] print(friends) Output: { “address”: “trichy” }
  • 74. By using pop() method Example: friends = { “name” : “ram” , “age” : 18 , “address”: “trichy” } friends . pop(“age”) print(frieds) Output: { “name” : “ram” , “address”: “trichy” }