SlideShare uma empresa Scribd logo
1 de 51
Baixar para ler offline
Python Programming
ing Problem Solving Approach
Reema Thareja
1
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
1
2
CHAPTER 8
Data Structures
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Data Structure: Sequence
3
A data structure is a group of data elements that are put together under one name. Data
structure defines a
particular way of storing and organizing data in a computer so that it can be used
efficiently.
Sequence is the most basic data structure in Python. In sequence, each element has a
specific index. This index value starts from zero and is automatically incremented for the
next element. In Python, sequence is the generic term for an ordered set. For example,
we have already studied strings which are a sequence of characters.
Python has some basic built-in functions that help programmers to manipulate elements
that form a part
of a sequence. These functions include finding the length of a sequence, finding the
largest and smallest
elements in a sequence, etc. Other operations that can be performed on a sequence
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Lists
4
List is a versatile data type available in Python. It is a sequence in which elements
are written as a list of
comma-separated values (items) between square brackets. The key feature of a list
is that it can have elements that belong to different data types. The syntax of
defining a list can be given as,
List_variable = [val1, val2,...]
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
es:
Access Values in Lists
5
Similar to strings, lists can also be sliced and concatenated. To access values in lists,
square brackets are used to slice along with the index or indices to get value stored at
that index. The syntax for the slice operation is given as, seq = List[start:stop:step]
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Updating Values in Lists
6
Once created, one or more elements of a list can be easily updated by giving the slice on
the left-hand side of the assignment operator. You can also append new values in the list
and remove existing value(s) from the list using the append() method and del statement
respectively.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Nested Lists
7
Nested list means a list within another list. We have already said that a list has
elements of different data types which can include even a list.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Cloning Lists
8
If you want to modify a list and also keep a copy of the original list, then you should
create a separate copy of the list (not just the reference). This process is called cloning.
The slice operation is used to clone a list.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Basic List Operations
9
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
List Methods
10
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Using Lists as Stack
11
Stack is an important data structure which stores its elements in an ordered manner.
Stack is a linear data structure which uses the same principle, i.e., the elements in a
stack are added and removed only from one end. Hence, a stack is called a LIFO (Last-In-
First-Out) data structure, as the element that was inserted last is the first one to be
taken out.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Using Lists as Stack
12
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Using Lists as Queues
13
Queue is an important data structure which stores its elements in an ordered manner. In
computer systems, the operating system makes full use of queues for the following
tasks.
• To maintain waiting lists for a single shared resource like printer, disk, CPU, etc.
• To transfer data asynchronously (data not necessarily received at same rate as sent)
between two processes (IO buffers), e.g., pipes, file IO, and sockets.
• As buffers on MP3 players and portable CD players, iPod playlist, etc.
• Handling interrupts.
• Queues are also used in the playlist of jukebox to add songs to the end and play from
the front of the list.
Queue supports three basic operations—insert, delete, and peep (or peek). In Python,
you can easily implement a queue by using the append() method to insert an element at
the end of the queue, pop() method with an index 0 to delete the first element from the
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Using Lists as Queues
14
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
List Comprehensions
15
Python also supports computed lists called list comprehensions having the following
syntax.
List = [expression for variable in sequence]
Where, the expression is evaluated once, for every item in the sequence.
List comprehensions help programmers to create lists in a concise way. This is mainly
beneficial to make new lists where each element is the obtained by applying some
operations to each member of another sequence or iterable. List comprehension is also
used to create a subsequence of those elements that satisfy a certain condition.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Looping in Lists
16
Python's for and in constructs are extremely useful especially when working with lists.
The for var in list statement is an easy way to access each element in a list (or any other
sequence). For example, in the
following code, the for loop is used to access each item in the list.
for i in list:
print(i)
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Using the enumerate() and range() Functions
17
enumerate() function is used when you want to print both index as well as an item in the
list. The function returns an enumerate object which contains the index and value of all
the items of the list as a tuple.
The range() function is used when you need to print index.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
es:
Using an Iterator
18
You can create an iterator using the built-in iter() function. The iterator is used to loop
over the elements of the list. For this, the iterator fetches the value and then
automatically points to the next element in the list when it is used with the next()
method.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
filter() Function
19
The filter() function constructs a list from those elements of the list for which a function
returns True. The
syntax of the filter() function is given as, filter(function, sequence)
As per the syntax, the filter() function returns a sequence that contains items from the
sequence for which the function is True. If sequence is a string, Unicode, or a tuple, then
the result will be of the same type;
otherwise, it is always a list.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
map() Function
20
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
The map() function applies a particular function to every element of a list. Its syntax is
same as the filter function
After applying the specified function on the sequence, the map() function returns the
modified list. The map() function calls function(item) for each item in the sequence and
returns a list of the return values.
Example: Program that adds 2 to every value in the list
reduce() Function
21
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
The reduce() function with syntax as given below returns a single value generated by
calling the function
on the first two items of the sequence, then on the result and the next item, and so on.
Example: Program to calculate the sum of values in a list using the reduce()
function
Tuple
22
Like lists, tuple is another data structure supported by Python. It is very similar to lists
but differs in two things.
• First, a tuple is a sequence of immutable objects. This means that while you can
change the value of one or more items in a list, you cannot change the values in a tuple.
• Second, tuples use parentheses to define its elements whereas lists use square
brackets.
Creating Tuple
Creating a tuple is very simple and almost similar to creating a list. For creating a tuple,
generally you need to just put the different comma-separated values within a
parentheses as shown below.
Tup1 = (val 1, val 2,...)
where val (or values) can be an integer, a floating number, a character, or a string.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Utility of Tuples
23
In real-world applications, tuples are extremely useful for representing records or
structures as we call
in other programming languages. These structures store related information about a
subject together.
The information belongs to different data types.
For example, a tuple that stores information about a student can have elements like
roll_no, name, course, total marks, avg, etc. Some built-in functions return a tuple. For
example, the divmod() function returns two values—quotient as well as the remainder
after performing the divide operation.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
es:
Accessing Values in a Tuple
24
Like other sequences (strings and lists) covered so far, indices in a tuple also starts at 0.
You can even perform
operations like slice, concatenate, etc. on a tuple. For example, to access values in tuple,
slice operation is used along with the index or indices to obtain value stored at that
index
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Deleting Elements in Tuple
25
Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course,
you can create a new tuple that has all elements in your tuple except the ones you don't
want (those you wanted to be deleted).
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
es:
Basic Tuple Operations
26
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Tuple Assignment
27
Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on
the left side of the assignment operator to be assigned values from a tuple given on the
right side of the assignment operator.
Each value is assigned to its respective variable. In case, an expression is specified on
the right side of the assignment operator, first that expression is evaluated and then
assignment is done.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Tuples for Returning Multiple Values and Nested
Tuples
28
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
es:
Checking the Index: index() method
29
The index of an element in the tuple can be obtained by using the index() method. If the
element being searched is not present in the list, then error is generated. The syntax of
index() is given as, list.index(obj) where, obj is the object to be found out.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
es:
count()Method and List Comprehension and Tuples
30
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
es:
Variable-length Argument Tuples
31
Many built-in functions like max(), min(), sum(), etc. use variable-length arguments since
these functions themselves do not know how many arguments will be passed to them. It
allows a function to accept a variable (different) number of arguments. This is especially
useful in defining functions that are applicable to a large variety of arguments. For
example, if you have a function that displays all the parameters passed to it, then even
the function does not know how many values it will be passed. In such cases, we use a
variable-length argument that begins with a '*' symbol. Any argument that starts with a
'*' symbol is known as gather and specifies a variable-length argument.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
The zip() Function
32
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
The zip() is a built-in function that takes two or more sequences and "zips" them into a
list of tuples. The tuple thus, formed has one element from each sequence.
Example: Program to show the use of zip() function
Advantages of Tuple over List
33
• Tuples are used to store values of different data types. Lists can however, store data
of similar data types.
• Since tuples are immutable, iterating through tuples is faster than iterating over a list.
This means that a
tuple performs better than a list.
• Tuples can be used as key for a dictionary but lists cannot be used as keys.
• Tuples are best suited for storing data that is write-protected.
• Tuples can be used in place of lists where the number of values is known and small.
• If you are passing a tuple as an argument to a function, then the potential for
unexpected behavior due to
aliasing gets reduced.
• Multiple values from a function can be returned using a tuple.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Sets
34
Sets is another data structure supported by Python. Basically, sets are same as lists but
with a difference that sets are lists with no duplicate entries. Technically, a set is a
mutable and an unordered collection of items. This means that we can easily add or
remove items from it.
A set is created by placing all the elements inside curly brackets {}, separated by comma
or by using the
built-in function set(). The syntax of creating a set can be given as,
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Example: To create a set, you can write,
Set Operations
35
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Set Operations
36
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Set Operations
37
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Set Operations
38
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Dictionaries
39
Dictionary is a data structure in which we store values as a pair of key and value. Each
key is separated from its value by a colon (:), and consecutive items are separated by
commas. The entire items in a dictionary are enclosed in curly brackets({}). The syntax
for defining a dictionary is
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
If there are many keys and values in dictionaries, then we can also write just one key-
value pair on a line
to make the code easier to read and understand. This is shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….}
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Accessing Values
40
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Adding and Modifying an Item in a Dictionary
41
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Modifying an Entry
42
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Deleting Items
43
You can delete one or more items using the del keyword. To delete or remove all the
items in just one statement, use the clear() function. Finally, to remove an entire
dictionary from the memory, we can gain
use the del statement as del Dict_name. The syntax to use the del statement can be
given as,
del dictionary_variable[key]
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Sorting Items and Looping over Items in a
Dictinonary
44
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
es:
Nested Dictionaries
45
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Exampl
e:
Built-in Dictionary Functions and Methods
46
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Built-in Dictionary Functions and Methods
47
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Built-in Dictionary Functions and Methods
48
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Difference between a List and a Dictionary
49
First, a list is an ordered set of items. But, a dictionary is a data structure that is used for
matching one item
(key) with another (value).
• Second, in lists, you can use indexing to access a particular item. But, these indexes
should be a number. In
dictionaries, you can use any type (immutable) of value as an index. For example, when
we write Dict['Name'], Name acts as an index but it is not a number but a string.
• Third, lists are used to look up a value whereas a dictionary is used to take one value
and look up another
value. For this reason, dictionary is also known as a lookup table.
Fourth, the key-value pair may not be displayed in the order in which it was specified
while defining the © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
String Formatting with Dictionaries
50
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Python also allows you to use string formatting feature with dictionaries. So you can use
%s, %d, %f, etc. to
represent string, integer, floating point number, or any other data.
Example: Program that uses string formatting feature to print the key-value pairs stored in the
dictionary
When to use which Data Structure?
51
• Use lists to store a collection of data that does not need random access.
• Use lists if the data has to be modified frequently.
• Use a set if you want to ensure that every element in the data structure must be
unique.
• Use tuples when you want that your data should not be altered.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.

Mais conteúdo relacionado

Semelhante a Ch-8.pdf

358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4sumitbardhan
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptxrohithprabhas1
 
Introduction to Data Structure
Introduction to Data StructureIntroduction to Data Structure
Introduction to Data StructureJazz Jinia Bhowmik
 
CS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfCS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfraji175286
 
Chapter 2.2 data structures
Chapter 2.2 data structuresChapter 2.2 data structures
Chapter 2.2 data structuressshhzap
 
Data structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdData structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdNimmi Weeraddana
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructuresNguync91368
 
Everything Technical on List in Python--
Everything Technical on List in Python--Everything Technical on List in Python--
Everything Technical on List in Python--Mars Devs
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptxselemonGamo
 
Data Structure.pdf
Data Structure.pdfData Structure.pdf
Data Structure.pdfMemeMiner
 
Ch 1 intriductions
Ch 1 intriductionsCh 1 intriductions
Ch 1 intriductionsirshad17
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS Adams Sidibe
 
Complete a C++ class implementation for a linked-list of sorted (asc.pdf
Complete a C++ class implementation for a linked-list of sorted (asc.pdfComplete a C++ class implementation for a linked-list of sorted (asc.pdf
Complete a C++ class implementation for a linked-list of sorted (asc.pdfshahidqamar17
 

Semelhante a Ch-8.pdf (20)

Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
 
DS_PPT.ppt
DS_PPT.pptDS_PPT.ppt
DS_PPT.ppt
 
Introduction to Data Structure
Introduction to Data StructureIntroduction to Data Structure
Introduction to Data Structure
 
CS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfCS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdf
 
Chapter 2.2 data structures
Chapter 2.2 data structuresChapter 2.2 data structures
Chapter 2.2 data structures
 
Data structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pdData structures and algorithms short note (version 14).pd
Data structures and algorithms short note (version 14).pd
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
Everything Technical on List in Python--
Everything Technical on List in Python--Everything Technical on List in Python--
Everything Technical on List in Python--
 
AI_2nd Lab.pptx
AI_2nd Lab.pptxAI_2nd Lab.pptx
AI_2nd Lab.pptx
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
1597380885789.ppt
1597380885789.ppt1597380885789.ppt
1597380885789.ppt
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
 
Data Structure.pdf
Data Structure.pdfData Structure.pdf
Data Structure.pdf
 
Ch 1 intriductions
Ch 1 intriductionsCh 1 intriductions
Ch 1 intriductions
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
 
Bt0065
Bt0065Bt0065
Bt0065
 
B T0065
B T0065B T0065
B T0065
 
Complete a C++ class implementation for a linked-list of sorted (asc.pdf
Complete a C++ class implementation for a linked-list of sorted (asc.pdfComplete a C++ class implementation for a linked-list of sorted (asc.pdf
Complete a C++ class implementation for a linked-list of sorted (asc.pdf
 

Mais de R.K.College of engg & Tech (15)

Module 5(Matplotlib and tkinter).pdf
Module 5(Matplotlib and tkinter).pdfModule 5(Matplotlib and tkinter).pdf
Module 5(Matplotlib and tkinter).pdf
 
Module 5(Numpy).pdf
Module 5(Numpy).pdfModule 5(Numpy).pdf
Module 5(Numpy).pdf
 
Module 5(Pandas).pdf
Module 5(Pandas).pdfModule 5(Pandas).pdf
Module 5(Pandas).pdf
 
Module IV_updated(old).pdf
Module IV_updated(old).pdfModule IV_updated(old).pdf
Module IV_updated(old).pdf
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
Python_Module_1.pdf
Python_Module_1.pdfPython_Module_1.pdf
Python_Module_1.pdf
 
Python for Data Analysis_ Data Wrangling with Pandas, Numpy, and Ipython ( PD...
Python for Data Analysis_ Data Wrangling with Pandas, Numpy, and Ipython ( PD...Python for Data Analysis_ Data Wrangling with Pandas, Numpy, and Ipython ( PD...
Python for Data Analysis_ Data Wrangling with Pandas, Numpy, and Ipython ( PD...
 
Ch-5.pdf
Ch-5.pdfCh-5.pdf
Ch-5.pdf
 
Ch-5.pdf
Ch-5.pdfCh-5.pdf
Ch-5.pdf
 
Ch-4.pdf
Ch-4.pdfCh-4.pdf
Ch-4.pdf
 
Ch-3.pdf
Ch-3.pdfCh-3.pdf
Ch-3.pdf
 
Creating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docxCreating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docx
 
Practice Program-9-Packages-Unit 4.docx
Practice Program-9-Packages-Unit 4.docxPractice Program-9-Packages-Unit 4.docx
Practice Program-9-Packages-Unit 4.docx
 
Unit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docxUnit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docx
 

Último

Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringJuanCarlosMorales19600
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
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
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
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
 
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
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
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
 
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
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 

Último (20)

Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineering
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
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
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
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
 
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...
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II 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
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.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)
 
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
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 

Ch-8.pdf

  • 1. Python Programming ing Problem Solving Approach Reema Thareja 1 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. 1
  • 2. 2 CHAPTER 8 Data Structures © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 3. Data Structure: Sequence 3 A data structure is a group of data elements that are put together under one name. Data structure defines a particular way of storing and organizing data in a computer so that it can be used efficiently. Sequence is the most basic data structure in Python. In sequence, each element has a specific index. This index value starts from zero and is automatically incremented for the next element. In Python, sequence is the generic term for an ordered set. For example, we have already studied strings which are a sequence of characters. Python has some basic built-in functions that help programmers to manipulate elements that form a part of a sequence. These functions include finding the length of a sequence, finding the largest and smallest elements in a sequence, etc. Other operations that can be performed on a sequence © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 4. Lists 4 List is a versatile data type available in Python. It is a sequence in which elements are written as a list of comma-separated values (items) between square brackets. The key feature of a list is that it can have elements that belong to different data types. The syntax of defining a list can be given as, List_variable = [val1, val2,...] © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl es:
  • 5. Access Values in Lists 5 Similar to strings, lists can also be sliced and concatenated. To access values in lists, square brackets are used to slice along with the index or indices to get value stored at that index. The syntax for the slice operation is given as, seq = List[start:stop:step] © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 6. Updating Values in Lists 6 Once created, one or more elements of a list can be easily updated by giving the slice on the left-hand side of the assignment operator. You can also append new values in the list and remove existing value(s) from the list using the append() method and del statement respectively. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 7. Nested Lists 7 Nested list means a list within another list. We have already said that a list has elements of different data types which can include even a list. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 8. Cloning Lists 8 If you want to modify a list and also keep a copy of the original list, then you should create a separate copy of the list (not just the reference). This process is called cloning. The slice operation is used to clone a list. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 9. Basic List Operations 9 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 10. List Methods 10 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 11. Using Lists as Stack 11 Stack is an important data structure which stores its elements in an ordered manner. Stack is a linear data structure which uses the same principle, i.e., the elements in a stack are added and removed only from one end. Hence, a stack is called a LIFO (Last-In- First-Out) data structure, as the element that was inserted last is the first one to be taken out. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 12. Using Lists as Stack 12 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 13. Using Lists as Queues 13 Queue is an important data structure which stores its elements in an ordered manner. In computer systems, the operating system makes full use of queues for the following tasks. • To maintain waiting lists for a single shared resource like printer, disk, CPU, etc. • To transfer data asynchronously (data not necessarily received at same rate as sent) between two processes (IO buffers), e.g., pipes, file IO, and sockets. • As buffers on MP3 players and portable CD players, iPod playlist, etc. • Handling interrupts. • Queues are also used in the playlist of jukebox to add songs to the end and play from the front of the list. Queue supports three basic operations—insert, delete, and peep (or peek). In Python, you can easily implement a queue by using the append() method to insert an element at the end of the queue, pop() method with an index 0 to delete the first element from the © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 14. Using Lists as Queues 14 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 15. List Comprehensions 15 Python also supports computed lists called list comprehensions having the following syntax. List = [expression for variable in sequence] Where, the expression is evaluated once, for every item in the sequence. List comprehensions help programmers to create lists in a concise way. This is mainly beneficial to make new lists where each element is the obtained by applying some operations to each member of another sequence or iterable. List comprehension is also used to create a subsequence of those elements that satisfy a certain condition. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 16. Looping in Lists 16 Python's for and in constructs are extremely useful especially when working with lists. The for var in list statement is an easy way to access each element in a list (or any other sequence). For example, in the following code, the for loop is used to access each item in the list. for i in list: print(i) © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 17. Using the enumerate() and range() Functions 17 enumerate() function is used when you want to print both index as well as an item in the list. The function returns an enumerate object which contains the index and value of all the items of the list as a tuple. The range() function is used when you need to print index. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl es:
  • 18. Using an Iterator 18 You can create an iterator using the built-in iter() function. The iterator is used to loop over the elements of the list. For this, the iterator fetches the value and then automatically points to the next element in the list when it is used with the next() method. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 19. filter() Function 19 The filter() function constructs a list from those elements of the list for which a function returns True. The syntax of the filter() function is given as, filter(function, sequence) As per the syntax, the filter() function returns a sequence that contains items from the sequence for which the function is True. If sequence is a string, Unicode, or a tuple, then the result will be of the same type; otherwise, it is always a list. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 20. map() Function 20 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. The map() function applies a particular function to every element of a list. Its syntax is same as the filter function After applying the specified function on the sequence, the map() function returns the modified list. The map() function calls function(item) for each item in the sequence and returns a list of the return values. Example: Program that adds 2 to every value in the list
  • 21. reduce() Function 21 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. The reduce() function with syntax as given below returns a single value generated by calling the function on the first two items of the sequence, then on the result and the next item, and so on. Example: Program to calculate the sum of values in a list using the reduce() function
  • 22. Tuple 22 Like lists, tuple is another data structure supported by Python. It is very similar to lists but differs in two things. • First, a tuple is a sequence of immutable objects. This means that while you can change the value of one or more items in a list, you cannot change the values in a tuple. • Second, tuples use parentheses to define its elements whereas lists use square brackets. Creating Tuple Creating a tuple is very simple and almost similar to creating a list. For creating a tuple, generally you need to just put the different comma-separated values within a parentheses as shown below. Tup1 = (val 1, val 2,...) where val (or values) can be an integer, a floating number, a character, or a string. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 23. Utility of Tuples 23 In real-world applications, tuples are extremely useful for representing records or structures as we call in other programming languages. These structures store related information about a subject together. The information belongs to different data types. For example, a tuple that stores information about a student can have elements like roll_no, name, course, total marks, avg, etc. Some built-in functions return a tuple. For example, the divmod() function returns two values—quotient as well as the remainder after performing the divide operation. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl es:
  • 24. Accessing Values in a Tuple 24 Like other sequences (strings and lists) covered so far, indices in a tuple also starts at 0. You can even perform operations like slice, concatenate, etc. on a tuple. For example, to access values in tuple, slice operation is used along with the index or indices to obtain value stored at that index © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 25. Deleting Elements in Tuple 25 Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course, you can create a new tuple that has all elements in your tuple except the ones you don't want (those you wanted to be deleted). © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl es:
  • 26. Basic Tuple Operations 26 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 27. Tuple Assignment 27 Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the left side of the assignment operator to be assigned values from a tuple given on the right side of the assignment operator. Each value is assigned to its respective variable. In case, an expression is specified on the right side of the assignment operator, first that expression is evaluated and then assignment is done. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 28. Tuples for Returning Multiple Values and Nested Tuples 28 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl es:
  • 29. Checking the Index: index() method 29 The index of an element in the tuple can be obtained by using the index() method. If the element being searched is not present in the list, then error is generated. The syntax of index() is given as, list.index(obj) where, obj is the object to be found out. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl es:
  • 30. count()Method and List Comprehension and Tuples 30 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl es:
  • 31. Variable-length Argument Tuples 31 Many built-in functions like max(), min(), sum(), etc. use variable-length arguments since these functions themselves do not know how many arguments will be passed to them. It allows a function to accept a variable (different) number of arguments. This is especially useful in defining functions that are applicable to a large variety of arguments. For example, if you have a function that displays all the parameters passed to it, then even the function does not know how many values it will be passed. In such cases, we use a variable-length argument that begins with a '*' symbol. Any argument that starts with a '*' symbol is known as gather and specifies a variable-length argument. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 32. The zip() Function 32 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. The zip() is a built-in function that takes two or more sequences and "zips" them into a list of tuples. The tuple thus, formed has one element from each sequence. Example: Program to show the use of zip() function
  • 33. Advantages of Tuple over List 33 • Tuples are used to store values of different data types. Lists can however, store data of similar data types. • Since tuples are immutable, iterating through tuples is faster than iterating over a list. This means that a tuple performs better than a list. • Tuples can be used as key for a dictionary but lists cannot be used as keys. • Tuples are best suited for storing data that is write-protected. • Tuples can be used in place of lists where the number of values is known and small. • If you are passing a tuple as an argument to a function, then the potential for unexpected behavior due to aliasing gets reduced. • Multiple values from a function can be returned using a tuple. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 34. Sets 34 Sets is another data structure supported by Python. Basically, sets are same as lists but with a difference that sets are lists with no duplicate entries. Technically, a set is a mutable and an unordered collection of items. This means that we can easily add or remove items from it. A set is created by placing all the elements inside curly brackets {}, separated by comma or by using the built-in function set(). The syntax of creating a set can be given as, © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Example: To create a set, you can write,
  • 35. Set Operations 35 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 36. Set Operations 36 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 37. Set Operations 37 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 38. Set Operations 38 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 39. Dictionaries 39 Dictionary is a data structure in which we store values as a pair of key and value. Each key is separated from its value by a colon (:), and consecutive items are separated by commas. The entire items in a dictionary are enclosed in curly brackets({}). The syntax for defining a dictionary is dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3} If there are many keys and values in dictionaries, then we can also write just one key- value pair on a line to make the code easier to read and understand. This is shown below. dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….} © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 40. Accessing Values 40 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 41. Adding and Modifying an Item in a Dictionary 41 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 42. Modifying an Entry 42 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 43. Deleting Items 43 You can delete one or more items using the del keyword. To delete or remove all the items in just one statement, use the clear() function. Finally, to remove an entire dictionary from the memory, we can gain use the del statement as del Dict_name. The syntax to use the del statement can be given as, del dictionary_variable[key] © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 44. Sorting Items and Looping over Items in a Dictinonary 44 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl es:
  • 45. Nested Dictionaries 45 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Exampl e:
  • 46. Built-in Dictionary Functions and Methods 46 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 47. Built-in Dictionary Functions and Methods 47 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 48. Built-in Dictionary Functions and Methods 48 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 49. Difference between a List and a Dictionary 49 First, a list is an ordered set of items. But, a dictionary is a data structure that is used for matching one item (key) with another (value). • Second, in lists, you can use indexing to access a particular item. But, these indexes should be a number. In dictionaries, you can use any type (immutable) of value as an index. For example, when we write Dict['Name'], Name acts as an index but it is not a number but a string. • Third, lists are used to look up a value whereas a dictionary is used to take one value and look up another value. For this reason, dictionary is also known as a lookup table. Fourth, the key-value pair may not be displayed in the order in which it was specified while defining the © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
  • 50. String Formatting with Dictionaries 50 © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED. Python also allows you to use string formatting feature with dictionaries. So you can use %s, %d, %f, etc. to represent string, integer, floating point number, or any other data. Example: Program that uses string formatting feature to print the key-value pairs stored in the dictionary
  • 51. When to use which Data Structure? 51 • Use lists to store a collection of data that does not need random access. • Use lists if the data has to be modified frequently. • Use a set if you want to ensure that every element in the data structure must be unique. • Use tuples when you want that your data should not be altered. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.