SlideShare a Scribd company logo
1 of 74
Data Structures in Python
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”)
“age”:18
print(frieds)
Output:
{ “name” : “ram” , “address”: “trichy” }

More Related Content

Similar to Unit - 4.ppt

Lists.pptx
Lists.pptxLists.pptx
Lists.pptxYagna15
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202Mahmoud Samir Fayed
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfAsst.prof M.Gokilavani
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210Mahmoud Samir Fayed
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptxChandanVatsa2
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir1
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212Mahmoud Samir Fayed
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptxSakith1
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_pythondeepalishinkar1
 
list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptxssuser8f0410
 

Similar to Unit - 4.ppt (20)

6. list
6. list6. list
6. list
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptx
 

More from Kongunadu College of Engineering and Technology (19)

Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
Unit V - ppt.pptx
 
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
C++ UNIT4.pptx
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
UNIT 4.pptx
UNIT 4.pptxUNIT 4.pptx
UNIT 4.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
UNIT 3.pptx
UNIT 3.pptxUNIT 3.pptx
UNIT 3.pptx
 
Unit - 1.ppt
Unit - 1.pptUnit - 1.ppt
Unit - 1.ppt
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Unit - 2.ppt
Unit - 2.pptUnit - 2.ppt
Unit - 2.ppt
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
U1.ppt
U1.pptU1.ppt
U1.ppt
 
U2.ppt
U2.pptU2.ppt
U2.ppt
 
U4.ppt
U4.pptU4.ppt
U4.ppt
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U3.pptx
U3.pptxU3.pptx
U3.pptx
 

Recently uploaded

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 

Recently uploaded (20)

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 

Unit - 4.ppt

  • 1. Data Structures in Python K.ANGURAJU AP / CSE
  • 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”) “age”:18 print(frieds) Output: { “name” : “ram” , “address”: “trichy” }