SlideShare a Scribd company logo
1 of 29
PYTHON DATA STRUCTURES
Mrs. K. V. Joshi
Assistant Professor,
SITCOE, Ichalkaranji
DATA STRUCTURES
 Lists
 Tuples
 Dictionaries
 Sets
2
LISTS
 Python’s most flexible, ordered collection data type
 Lists can contain any sort of object: numbers, strings, even
other lists
 Python lists are:
 Ordered collection of arbitrary objects
 Accessed by offset
 Variable length, heterogeneous, arbitrarily nestable
 Of the category mutable sequence
3
CREATING A LIST:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
Output:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
4
UPDATING A LIST:
list = ['physics', 'chemistry', 1997, 2000]
print("Value available at index 2 :”)
print list[2]
list[2] = 2001
Print("New value available at index 2 :”)
print list[2]
Output:
Value available at index 2 :
1997
New value available at index 2 :
2001 5
DELETING A LIST:
list1 = ['physics', 'chemistry', 1997, 2000]
print list1
del list1[2]
print ("After deleting value at index 2 :”)
print list1
Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000] 6
BUILT-IN LIST METHODS
 len( )
 max( )
 min( )
 append( )
 count( )
 extend( )
 index( )
 insert( )
 pop( )
 remove( )
 reverse( ) 7
TUPLES
 Tuples construct simple group of objects.
 They are immutable
 Usually written as a series of items in parenthesis.
 Tuples are:
 Ordered collection of arbitrary objects
 Accessed by offset
 Fixed length, heterogeneous, arbitrarily nestable
 Of the category immutable sequence
8
CREATING A TUPLE:
 Creating a tuple is as simple as putting different comma-
separated values. Or you can put these comma-separated
values between parentheses also.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
 The empty tuple is written as two parentheses containing
nothing. For example − tup1 = ( )
 To write a tuple containing a single value you have to
include a comma, even though there is only one value −
tup1 = (50,) 9
ACCESSING VALUES IN TUPLES:
 To access values in tuple, use the square brackets
for slicing along with the index or indices to obtain
value available at that index.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
When the above code is executed, it produces the
following result −
tup1[0]: physics tup2[1:5]: [2, 3, 4, 5] 10
UPDATING TUPLES
Tuples are immutable which means you cannot
update or change the values of tuple elements. But,
you are able to take portions of existing tuples to
create new tuples as the following example
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print tup3
Output:
(12, 34.56, 'abc', 'xyz') 11
DELETING TUPLE ELEMENTS
Removing individual tuple elements is not possible. But, we can
delete the entire tuple using the del statement.
For example −
tup = ('physics', 'chemistry', 1997, 2000)
print(tup)
del tup
print (0)"After deleting tup : "
print (tup)
Output:
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup
NameError: name 'tup' is not defined
12
BUILT-IN TUPLE METHODS
 len( )
 max( )
 min( )
 tuple( )
13
DICTIONARIES
 The dictionary contains Key-value pairs as its data
elements.
 Each key is separated from its value by a colon (:),
the items are separated by commas, and the whole
thing is enclosed in curly braces.
 An empty dictionary without any items is written
with just two curly braces, like this: { }.
 Dictionaries are:
 Unordered collection of arbitrary objects
 Accessed by key, not offset
 Variable length, heterogeneous, arbitrarily nestable
 Of the category mutable mapping
14
ACCESSING VALUES IN DICTIONARY:
To access dictionary elements, you can use the
square brackets along with the key to obtain its value.
For example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Output:
dict['Name']: Zara
dict['Age']: 7
15
UPDATING DICTIONARY
You can update a dictionary by adding a new entry or a
key-value pair, modifying an existing entry, or deleting an
existing entry as shown below in the simple example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8
# update existing entry
dict['School'] = "DPS School"
# Add new entry
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])
Output:
dict['Age']: 8 dict['School']: DPS School
16
DELETING DICTIONARY ELEMENTS
 You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.
 To explicitly remove an entire dictionary, just use the del statement.
For example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear( ) # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Output:
Note that an exception is raised because after del dict dictionary does not exist
any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age']
TypeError: 'type' object is unsubscriptable
17
BUILT-IN DICTIONARY METHODS
 len( )
 str( )
 type( )
 clear( )
 copy( )
 fromkeys( )
 get( )
 has_key( )
 items( )
 keys( )
 setdefault( )
 update( ) 18
SETS
 Set is an unordered collection of collection of
unique and immutable objects that support
operations corresponding to mathematical set
theory.
 By definition, an items appears only once in a set,
no matter how many times it is added
 Sets are:
 Unordered collection of arbitrary objects
 Of the category immutable objects
19
CREATING A SET
A set is created by using the set( ) function or placing
all the elements within a pair of curly braces.
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
Output:
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
set(['Jan', 'Mar', 'Feb']) set([17, 21, 22])
20
ACCESSING VALUES IN A SET
We cannot access individual values in a set. We can only
access all the elements together as shown above. But we
can also get a list of individual elements by looping through
the set.
For Example –
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for d in Days: print(d)
Output:
Wed Sun Fri Tue Mon Thu Sat
21
ADDING ITEMS TO A SET
We can add elements to a set by using add() method.
There is no specific index attached to the newly
added element.
For example-
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.add("Sun")
print(Days)
Output:
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) 22
REMOVING ITEM FROM A SET
We can remove elements from a set by using
discard() method. There is no specific index attached
to the newly added element.
For example –
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.discard("Sun")
print(Days)
Output:
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
23
UNION OF SETS
 The union operation on two sets produces a new
set containing all the distinct elements from both
the sets.
 In the below example the element “Wed” is present
in both the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays
= DaysA|DaysB
print(AllDays)
Output:
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) 24
INTERSECTION OF SET
 The intersection operation on two sets produces a
new set containing only the common elements from
both the sets.
 In the below example the element “Wed” is present
in both the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)
Output:
set(['Wed']) 25
DIFFERENCE OF SETS:
 The difference operation on two sets produces a
new set containing only the elements from the first
set and none from the second set.
 In the below example the element “Wed” is present
in both the sets so it will not be found in the result
set.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB print(AllDays)
Output:
set(['Mon', 'Tue']) 26
COMPARE SETS
We can check if a given set is a subset or superset of another
set. The result is True or False depending on the elements
present in the sets.
For Example –
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) SubsetRes
= DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)
Output:
True True 27
BUILT-IN SET METHODS AND OPERATIONS
 add( )
 remove( )
 union
 intersection
 difference
 symmetric difference
 size
28
29

More Related Content

What's hot (19)

Chapter2
Chapter2Chapter2
Chapter2
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Array
ArrayArray
Array
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason Swartz
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Functional es6
Functional es6Functional es6
Functional es6
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Laporan Resmi Algoritma dan Struktur Data :
Laporan Resmi Algoritma dan Struktur Data : Laporan Resmi Algoritma dan Struktur Data :
Laporan Resmi Algoritma dan Struktur Data :
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 

Similar to Python data structures

python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdfAshaWankar1
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docSrikrishnaVundavalli
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfomprakashmeena48
 
The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181Mahmoud Samir Fayed
 
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
 
The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180Mahmoud Samir Fayed
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPTAlbin562191
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structuresMohd Arif
 
The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212Mahmoud Samir Fayed
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in pythonCeline George
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysMaulen Bale
 

Similar to Python data structures (20)

python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181
 
Python list
Python listPython list
Python list
 
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
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
Array
ArrayArray
Array
 
07012023.pptx
07012023.pptx07012023.pptx
07012023.pptx
 
The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPT
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
Arrays
ArraysArrays
Arrays
 
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 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212
 
Python - Lecture 4
Python - Lecture 4Python - Lecture 4
Python - Lecture 4
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Array
ArrayArray
Array
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 

Recently uploaded

Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...drmkjayanthikannan
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksMagic Marks
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdfKamal Acharya
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 

Recently uploaded (20)

Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 

Python data structures

  • 1. PYTHON DATA STRUCTURES Mrs. K. V. Joshi Assistant Professor, SITCOE, Ichalkaranji
  • 2. DATA STRUCTURES  Lists  Tuples  Dictionaries  Sets 2
  • 3. LISTS  Python’s most flexible, ordered collection data type  Lists can contain any sort of object: numbers, strings, even other lists  Python lists are:  Ordered collection of arbitrary objects  Accessed by offset  Variable length, heterogeneous, arbitrarily nestable  Of the category mutable sequence 3
  • 4. CREATING A LIST: list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] print ("list1[0]: ", list1[0]) print ("list2[1:5]: ", list2[1:5]) Output: list1[0]: physics list2[1:5]: [2, 3, 4, 5] 4
  • 5. UPDATING A LIST: list = ['physics', 'chemistry', 1997, 2000] print("Value available at index 2 :”) print list[2] list[2] = 2001 Print("New value available at index 2 :”) print list[2] Output: Value available at index 2 : 1997 New value available at index 2 : 2001 5
  • 6. DELETING A LIST: list1 = ['physics', 'chemistry', 1997, 2000] print list1 del list1[2] print ("After deleting value at index 2 :”) print list1 Output: ['physics', 'chemistry', 1997, 2000] After deleting value at index 2 : ['physics', 'chemistry', 2000] 6
  • 7. BUILT-IN LIST METHODS  len( )  max( )  min( )  append( )  count( )  extend( )  index( )  insert( )  pop( )  remove( )  reverse( ) 7
  • 8. TUPLES  Tuples construct simple group of objects.  They are immutable  Usually written as a series of items in parenthesis.  Tuples are:  Ordered collection of arbitrary objects  Accessed by offset  Fixed length, heterogeneous, arbitrarily nestable  Of the category immutable sequence 8
  • 9. CREATING A TUPLE:  Creating a tuple is as simple as putting different comma- separated values. Or you can put these comma-separated values between parentheses also. For example − tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 ) tup3 = "a", "b", "c", "d"  The empty tuple is written as two parentheses containing nothing. For example − tup1 = ( )  To write a tuple containing a single value you have to include a comma, even though there is only one value − tup1 = (50,) 9
  • 10. ACCESSING VALUES IN TUPLES:  To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example − tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup1[0]: ", tup1[0]) print ("tup2[1:5]: ", tup2[1:5]) When the above code is executed, it produces the following result − tup1[0]: physics tup2[1:5]: [2, 3, 4, 5] 10
  • 11. UPDATING TUPLES Tuples are immutable which means you cannot update or change the values of tuple elements. But, you are able to take portions of existing tuples to create new tuples as the following example tup1 = (12, 34.56) tup2 = ('abc', 'xyz') # Following action is not valid for tuples # tup1[0] = 100 # So let's create a new tuple as follows tup3 = tup1 + tup2 print tup3 Output: (12, 34.56, 'abc', 'xyz') 11
  • 12. DELETING TUPLE ELEMENTS Removing individual tuple elements is not possible. But, we can delete the entire tuple using the del statement. For example − tup = ('physics', 'chemistry', 1997, 2000) print(tup) del tup print (0)"After deleting tup : " print (tup) Output: ('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last): File "test.py", line 9, in <module> print tup NameError: name 'tup' is not defined 12
  • 13. BUILT-IN TUPLE METHODS  len( )  max( )  min( )  tuple( ) 13
  • 14. DICTIONARIES  The dictionary contains Key-value pairs as its data elements.  Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces.  An empty dictionary without any items is written with just two curly braces, like this: { }.  Dictionaries are:  Unordered collection of arbitrary objects  Accessed by key, not offset  Variable length, heterogeneous, arbitrarily nestable  Of the category mutable mapping 14
  • 15. ACCESSING VALUES IN DICTIONARY: To access dictionary elements, you can use the square brackets along with the key to obtain its value. For example − dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print ("dict['Name']: ", dict['Name']) print ("dict['Age']: ", dict['Age']) Output: dict['Name']: Zara dict['Age']: 7 15
  • 16. UPDATING DICTIONARY You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8 # update existing entry dict['School'] = "DPS School" # Add new entry print("dict['Age']: ", dict['Age']) print("dict['School']: ", dict['School']) Output: dict['Age']: 8 dict['School']: DPS School 16
  • 17. DELETING DICTIONARY ELEMENTS  You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.  To explicitly remove an entire dictionary, just use the del statement. For example − dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name'] # remove entry with key 'Name' dict.clear( ) # remove all entries in dict del dict # delete entire dictionary print ("dict['Age']: ", dict['Age']) print ("dict['School']: ", dict['School']) Output: Note that an exception is raised because after del dict dictionary does not exist any more − dict['Age']: Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age'] TypeError: 'type' object is unsubscriptable 17
  • 18. BUILT-IN DICTIONARY METHODS  len( )  str( )  type( )  clear( )  copy( )  fromkeys( )  get( )  has_key( )  items( )  keys( )  setdefault( )  update( ) 18
  • 19. SETS  Set is an unordered collection of collection of unique and immutable objects that support operations corresponding to mathematical set theory.  By definition, an items appears only once in a set, no matter how many times it is added  Sets are:  Unordered collection of arbitrary objects  Of the category immutable objects 19
  • 20. CREATING A SET A set is created by using the set( ) function or placing all the elements within a pair of curly braces. Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) Months={"Jan","Feb","Mar"} Dates={21,22,17} print(Days) print(Months) print(Dates) Output: set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) set(['Jan', 'Mar', 'Feb']) set([17, 21, 22]) 20
  • 21. ACCESSING VALUES IN A SET We cannot access individual values in a set. We can only access all the elements together as shown above. But we can also get a list of individual elements by looping through the set. For Example – Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) for d in Days: print(d) Output: Wed Sun Fri Tue Mon Thu Sat 21
  • 22. ADDING ITEMS TO A SET We can add elements to a set by using add() method. There is no specific index attached to the newly added element. For example- Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"]) Days.add("Sun") print(Days) Output: set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) 22
  • 23. REMOVING ITEM FROM A SET We can remove elements from a set by using discard() method. There is no specific index attached to the newly added element. For example – Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"]) Days.discard("Sun") print(Days) Output: set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) 23
  • 24. UNION OF SETS  The union operation on two sets produces a new set containing all the distinct elements from both the sets.  In the below example the element “Wed” is present in both the sets. DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA|DaysB print(AllDays) Output: set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) 24
  • 25. INTERSECTION OF SET  The intersection operation on two sets produces a new set containing only the common elements from both the sets.  In the below example the element “Wed” is present in both the sets. DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA & DaysB print(AllDays) Output: set(['Wed']) 25
  • 26. DIFFERENCE OF SETS:  The difference operation on two sets produces a new set containing only the elements from the first set and none from the second set.  In the below example the element “Wed” is present in both the sets so it will not be found in the result set. DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA - DaysB print(AllDays) Output: set(['Mon', 'Tue']) 26
  • 27. COMPARE SETS We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets. For Example – DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) SubsetRes = DaysA <= DaysB SupersetRes = DaysB >= DaysA print(SubsetRes) print(SupersetRes) Output: True True 27
  • 28. BUILT-IN SET METHODS AND OPERATIONS  add( )  remove( )  union  intersection  difference  symmetric difference  size 28
  • 29. 29