SlideShare a Scribd company logo
1
Python Programming
Using Problem Solving Approach
Reema Thareja
1
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
2
CHAPTER 8
Data Structures
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
3
Data Structure: Sequence
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 include indexing, slicing,
adding, multiplying, and checking for membership.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Lists
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. 5
AccessValues in Lists
6
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
Exam
ple:
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 7
8
UpdatingValues in Lists
In Python, lists are mutable, which means you can
directly update their elements without creating a new
list. You can update values in a list by accessing
elements using their index and assigning new values.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
9
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 10
1. Using Indexing to Update an Element
You can directly update an element in a list by referring to
its index.
my_list = [10, 20, 30, 40, 50]
my_list[2] = 100
print(my_list)
Output:
Copy code
[10, 20, 100, 40, 50]
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 11
2. Using append() to Add a New Element
If you want to add a new element to the end of the list, you can use the
append() method.
Example: Adding a new item to the list
my_list = [10, 20, 30, 40]
my_list.append(50) # Adding 50 to the end of the list
print(my_list)
Output:
[10, 20, 30, 40, 50]
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 12
3. Using insert() to Insert an Element at a Specific Index
The insert() method allows you to insert an element at any specific index
in the list.
Example:
my_list = [10, 20, 30, 40]
my_list.insert(2, 25) # Insert 25 at index 2
print(my_list)
Output:
[10, 20, 25, 30, 40]
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 13
4. Using remove() to Remove an Element by Value
You can remove an element from the list by specifying its value
using the remove() method.
my_list = [10, 20, 30, 40, 50]
my_list.remove(30) # Remove the element with the value 30
print(my_list)
Output:
[10, 20, 40, 50]
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 14
5. Using pop() to Remove an Element by Index
The pop() method allows you to remove and return an element at a specific index.
Example:
my_list = [10, 20, 30, 40, 50]
popped_value = my_list.pop(2) # Remove and return the element at index 2 (which
is 30)
print(my_list)
print("Popped value:", popped_value)
Output:
[10, 20, 40, 50]
Popped value: 30
15
Nested Lists
A nested list is simply a list that contains other lists as its
elements.These inner lists can also contain other lists, creating a
multi-level structure. Nested lists are useful when you need to
represent more complex data structures, like matrices (2D lists) or
other hierarchical data.
.
Example:
nested_list = [ [1, 2, 3], [4, 5, 6],[7, 8, 9] ]
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 16
Accessing Elements in a Nested List:
To access elements in a nested list, you use multiple indices: the first index
accesses the outer list, and the second index accesses the element within the inner
list.
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(nested_list[0]) # Output: [1, 2, 3]
print(nested_list[0][1]) # Output: 2
print(nested_list[2][2])
. 17
Nested List Example (Matrix Representation):
A common use of nested lists is to represent a matrix (2D array), where each
sublist represents a row in the matrix.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # Output: 6
matrix[2][0] = 100
print(matrix) # Output: [[1, 2, 3], [4, 5, 6], [100, 8, 9]]
18
ITERATION CONCEPT IN LIST
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 19
WHILE LOOP
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 20
USING FOR LOOP
my_list = ["a", "b", "c", "d"]
for i in range(len(my_list)):
print(f"Index {i}: {my_list[i]}")
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 21
OUTPUT
Index 0: a
Index 1: b
Index 2: c
Index 3: d
22
Cloning Lists
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.
Example:
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 23
24
Basic List Operations
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
25
List Methods
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Using Lists as Stack
26
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.
27
Using Lists as Stack
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
28
Using Lists as Queues
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 queue, and slice operation to print the value of
the last the element in the queue. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
29
Using Lists as Queues
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
30
List Comprehensions
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.
Example:
31
Looping in Lists
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.
Example:
32
Using the enumerate() and range() Functions
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.
Examples:
33
Using an Iterator
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.
Example:
34
filter() Function
The filter() function constructs a list from those elements of the list for which a function returnsTrue.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 isTrue. 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.
Example:
35
map() Function
© 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
36
reduce() Function
© 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
37
Tuple
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.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 38
CreatingTuple
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. 39
40
AccessingValues in aTuple
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.
Example:
41
Deleting Elements inTuple
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.
Examples:
42
BasicTuple Operations
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
43
Tuple Assignment
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.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 44
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 45
NESTED TUPLES
46
The zip() Function
© 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
47
Advantages ofTuple over List
• 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.
• Tuples are used to format strings.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
48
Sets
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,
49
Set Operations
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
50
Set Operations
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
51
Set Operations
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
52
Set Operations
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
53
Dictionaries
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}
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 54
55
AccessingValues
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
56
Adding an Item in a Dictionary
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
57
Modifying an Entry
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
58
Deleting Items
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.
Example:
59
Nested Dictionaries
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
60
Sorting Items and Looping over Items in a Dictinonary
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 61
62
Built-in Dictionary Functions and Methods
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
63
Built-in Dictionary Functions and Methods
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
64
Built-in Dictionary Functions and Methods
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
65
Difference between a List and a Dictionary
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
dictionary.This is because Python uses complex algorithms (called hashing) to provide fast access to the items
stored in the dictionary.This also makes dictionary preferable to use over a list of tuples.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
66
String Formatting with Dictionaries
© 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
67
When to use which Data Structure?
• 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.

More Related Content

Similar to PROBLEM SOLVING AND PYTHON PROGRAMMING PPT (20)

Python lists
Python listsPython lists
Python lists
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Datastructures using c++
Datastructures using c++Datastructures using c++
Datastructures using c++
Gopi Nath
 
EC2311 – Data Structures and C Programming
EC2311 – Data Structures and C ProgrammingEC2311 – Data Structures and C Programming
EC2311 – Data Structures and C Programming
Padma Priya
 
DSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdfDSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdf
Bharati Vidyapeeth COE, Navi Mumbai
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
Python PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptxPython PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptx
NeyXmarXd
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
Panimalar Engineering College
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data Collection
JoseTanJr
 
Data Structure
Data Structure Data Structure
Data Structure
Ibrahim MH
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
Mahmoud Samir Fayed
 
Module 2-Lists,Tuple and Dictionary Final by Dr.SV (1).pdf
Module 2-Lists,Tuple and Dictionary Final by Dr.SV (1).pdfModule 2-Lists,Tuple and Dictionary Final by Dr.SV (1).pdf
Module 2-Lists,Tuple and Dictionary Final by Dr.SV (1).pdf
SURESHA V
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
Hanif Durad
 
fundamental of python --- vivek singh shekawat
fundamental  of python --- vivek singh shekawatfundamental  of python --- vivek singh shekawat
fundamental of python --- vivek singh shekawat
shekhawatasshp
 
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
FjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhlFjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
Borraramkumar
 
Python for beginners
Python for beginnersPython for beginners
Python for beginners
Ali Huseyn Aliyev
 
General Data structures
General Data structuresGeneral Data structures
General Data structures
Youssef Elsalhawy
 
Python list
Python listPython list
Python list
ArchanaBhumkar
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
RAJASEKHARV8
 
Datastructures using c++
Datastructures using c++Datastructures using c++
Datastructures using c++
Gopi Nath
 
EC2311 – Data Structures and C Programming
EC2311 – Data Structures and C ProgrammingEC2311 – Data Structures and C Programming
EC2311 – Data Structures and C Programming
Padma Priya
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
Python PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptxPython PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptx
NeyXmarXd
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data Collection
JoseTanJr
 
Data Structure
Data Structure Data Structure
Data Structure
Ibrahim MH
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
Mahmoud Samir Fayed
 
Module 2-Lists,Tuple and Dictionary Final by Dr.SV (1).pdf
Module 2-Lists,Tuple and Dictionary Final by Dr.SV (1).pdfModule 2-Lists,Tuple and Dictionary Final by Dr.SV (1).pdf
Module 2-Lists,Tuple and Dictionary Final by Dr.SV (1).pdf
SURESHA V
 
fundamental of python --- vivek singh shekawat
fundamental  of python --- vivek singh shekawatfundamental  of python --- vivek singh shekawat
fundamental of python --- vivek singh shekawat
shekhawatasshp
 
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
FjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhlFjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
Borraramkumar
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
RAJASEKHARV8
 

Recently uploaded (20)

Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Ad

PROBLEM SOLVING AND PYTHON PROGRAMMING PPT

  • 1. 1 Python Programming Using Problem Solving Approach Reema Thareja 1 © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 2. 2 CHAPTER 8 Data Structures © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 3. 3 Data Structure: Sequence 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 include indexing, slicing, adding, multiplying, and checking for membership. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 4. Lists 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,...]
  • 5. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 5
  • 6. AccessValues in Lists 6 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 Exam ple:
  • 7. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 7
  • 8. 8 UpdatingValues in Lists In Python, lists are mutable, which means you can directly update their elements without creating a new list. You can update values in a list by accessing elements using their index and assigning new values. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 9. 9
  • 10. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 10 1. Using Indexing to Update an Element You can directly update an element in a list by referring to its index. my_list = [10, 20, 30, 40, 50] my_list[2] = 100 print(my_list) Output: Copy code [10, 20, 100, 40, 50]
  • 11. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 11 2. Using append() to Add a New Element If you want to add a new element to the end of the list, you can use the append() method. Example: Adding a new item to the list my_list = [10, 20, 30, 40] my_list.append(50) # Adding 50 to the end of the list print(my_list) Output: [10, 20, 30, 40, 50]
  • 12. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 12 3. Using insert() to Insert an Element at a Specific Index The insert() method allows you to insert an element at any specific index in the list. Example: my_list = [10, 20, 30, 40] my_list.insert(2, 25) # Insert 25 at index 2 print(my_list) Output: [10, 20, 25, 30, 40]
  • 13. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 13 4. Using remove() to Remove an Element by Value You can remove an element from the list by specifying its value using the remove() method. my_list = [10, 20, 30, 40, 50] my_list.remove(30) # Remove the element with the value 30 print(my_list) Output: [10, 20, 40, 50]
  • 14. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 14 5. Using pop() to Remove an Element by Index The pop() method allows you to remove and return an element at a specific index. Example: my_list = [10, 20, 30, 40, 50] popped_value = my_list.pop(2) # Remove and return the element at index 2 (which is 30) print(my_list) print("Popped value:", popped_value) Output: [10, 20, 40, 50] Popped value: 30
  • 15. 15 Nested Lists A nested list is simply a list that contains other lists as its elements.These inner lists can also contain other lists, creating a multi-level structure. Nested lists are useful when you need to represent more complex data structures, like matrices (2D lists) or other hierarchical data. . Example: nested_list = [ [1, 2, 3], [4, 5, 6],[7, 8, 9] ]
  • 16. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 16 Accessing Elements in a Nested List: To access elements in a nested list, you use multiple indices: the first index accesses the outer list, and the second index accesses the element within the inner list. nested_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(nested_list[0]) # Output: [1, 2, 3] print(nested_list[0][1]) # Output: 2 print(nested_list[2][2])
  • 17. . 17 Nested List Example (Matrix Representation): A common use of nested lists is to represent a matrix (2D array), where each sublist represents a row in the matrix. Example: matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[1][2]) # Output: 6 matrix[2][0] = 100 print(matrix) # Output: [[1, 2, 3], [4, 5, 6], [100, 8, 9]]
  • 19. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 19 WHILE LOOP
  • 20. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 20 USING FOR LOOP my_list = ["a", "b", "c", "d"] for i in range(len(my_list)): print(f"Index {i}: {my_list[i]}")
  • 21. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 21 OUTPUT Index 0: a Index 1: b Index 2: c Index 3: d
  • 22. 22 Cloning Lists 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. Example:
  • 23. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 23
  • 24. 24 Basic List Operations © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 25. 25 List Methods © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 26. Using Lists as Stack 26 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.
  • 27. 27 Using Lists as Stack © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 28. 28 Using Lists as Queues 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 queue, and slice operation to print the value of the last the element in the queue. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 29. 29 Using Lists as Queues © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 30. 30 List Comprehensions 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. Example:
  • 31. 31 Looping in Lists 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. Example:
  • 32. 32 Using the enumerate() and range() Functions 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. Examples:
  • 33. 33 Using an Iterator 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. Example:
  • 34. 34 filter() Function The filter() function constructs a list from those elements of the list for which a function returnsTrue.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 isTrue. 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. Example:
  • 35. 35 map() Function © 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
  • 36. 36 reduce() Function © 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
  • 37. 37 Tuple 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. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 38. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 38 CreatingTuple 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.
  • 39. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 39
  • 40. 40 AccessingValues in aTuple 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. Example:
  • 41. 41 Deleting Elements inTuple 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. Examples:
  • 42. 42 BasicTuple Operations © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 43. 43 Tuple Assignment 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.
  • 44. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 44
  • 45. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 45 NESTED TUPLES
  • 46. 46 The zip() Function © 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
  • 47. 47 Advantages ofTuple over List • 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. • Tuples are used to format strings. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 48. 48 Sets 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,
  • 49. 49 Set Operations © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 50. 50 Set Operations © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 51. 51 Set Operations © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 52. 52 Set Operations © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 53. 53 Dictionaries 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} © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 54. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 54
  • 55. 55 AccessingValues © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 56. 56 Adding an Item in a Dictionary © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 57. 57 Modifying an Entry © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 58. 58 Deleting Items 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. Example:
  • 59. 59 Nested Dictionaries © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 60. 60 Sorting Items and Looping over Items in a Dictinonary © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 61. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 61
  • 62. 62 Built-in Dictionary Functions and Methods © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 63. 63 Built-in Dictionary Functions and Methods © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 64. 64 Built-in Dictionary Functions and Methods © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 65. 65 Difference between a List and a Dictionary 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 dictionary.This is because Python uses complex algorithms (called hashing) to provide fast access to the items stored in the dictionary.This also makes dictionary preferable to use over a list of tuples. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 66. 66 String Formatting with Dictionaries © 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
  • 67. 67 When to use which Data Structure? • 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.