0% found this document useful (0 votes)
32 views130 pages

Unit 3

The document provides an overview of Python's collection data types, focusing on lists, tuples, sets, and dictionaries. It explains the characteristics, creation, and manipulation of lists, including built-in functions and methods for list operations. Additionally, it covers concepts such as list comprehension, slicing, and the mutability of lists, along with examples of inputting and copying lists.

Uploaded by

colab178178
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views130 pages

Unit 3

The document provides an overview of Python's collection data types, focusing on lists, tuples, sets, and dictionaries. It explains the characteristics, creation, and manipulation of lists, including built-in functions and methods for list operations. Additionally, it covers concepts such as list comprehension, slicing, and the mutability of lists, along with examples of inputting and copying lists.

Uploaded by

colab178178
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 130

UNIT -3

Python Collections
There are four collection data types in the Python programming
language:
• List:
It is a collection which is ordered and changeable. Allows
duplicate members.
• Tuple:
It is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set:
It is a collection which is unordered and unindexed. No duplicate
members
• Dictionary :
It is a collection which is unordered, changeable and indexed. No
duplicate members.
Introduction
• Programs commonly need to store a large number of values.
Suppose, for instance, that you need to read 100 numbers,
compute their average, and then find out how many of the
numbers are above the average.
• Your program first reads the numbers and computes their
average, then compares each number with the average to
determine whether it is above the average.
• In order to accomplish this task, the numbers must all be stored
in variables.
• To do this, you would have to create 100 variables and
repeatedly write almost identical code 100 times. Writing a
program this way is impractical. So, how do you solve this
problem?
List
• A list can store a collection of data of any size

• Lists are just like the arrays, declared in other languages.

• Lists need not be homogeneous always which makes it a most powerful


tool in Python.
• A single list may contain DataTypes like Integers, Strings, as well as Objects.

• Lists are mutable, and hence, they can be altered even after their creation.

• List in Python are ordered and have a definite count.

List: A list is a built-in sequence type in Python, defined by the list class. It's a
collection of ordered, mutable elements that can be of different data
types.
LIST BASICS
Creation of Lists
Creating list using the list class with the list() constructor
list1 = list() # Create an empty list
list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"]) # Create a list with strings
list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c,d
For convenience, you may create a list using the following syntax:

list1 = [] # Same as list()


list2 = [2, 3, 4] # Same as list([2, 3, 4])
list3 = ["red", "green"] # Same as list(["red", "green"])

6
How to Create Lists
• The elements in a list are separated by commas and are enclosed by a pair of
brackets ([]).
Syntax:
list_name=[list_element1,list_element2,list_element3,……]
Ex:
list = [2, "three", 4]
list 1= [“Hi",6 , "three", 4]
list2=[10,20,[40,60],"hai",80,[20,"python"]]
list3=[]

• A list within another list is said to be nested and the inner list is often called
a sublist.
• Finally, there is a special list that contains no elements. It is called the empty
list and is denoted [].
Note:
A list can contain the elements of same type or mixed type
Strings
• A String is a sequence of characters.

• In python, strings can be created by enclosing the character or the

sequence of characters in the quotes

• String in python are surrounded by either single quotation marks, or

double quotation marks or triple quotation marks.

‘Hello’ or “Hello“ or ‘’’ Hello’’’

• We can display a string in python by using print() function


Ex:
print("hello")
print('welcome to Python Class')
print('''Strings''')
List Is a Sequence Type

• Strings and lists are sequence types in Python.


– A string is a sequence of characters,
– while a list is a sequence of any elements.

9
Python Built-in functions of list
“len()” function
The len() function returns the number of items
(length) in a list
Python Built-in functions of list
“max()” function
Calculates maximum of all the elements in the List
Syntax: max(List)
Python Built-in functions of list
“min()” function
Calculates minimum of all the elements in the List
Syntax: min(List)
Python Built-in functions of list
“sum() “function
Calculates sum of all the elements of List.
Syntax: sum(List)
Note: Sum is calculated only for Numeric values, elsewise throws TypeError.
Python Built-in functions of list
random.shuffle() function
Shuffle a list (reorganize the order of the list items)
items.
The shuffle() method takes a sequence (list, string,
or tuple) and reorganize the order of the items.
Python Built-in functions
The List operators
in operator
– The ‘in’ operator is used to check if a value exists in the list or
not.
– Evaluates to true if the element present in the list and false
otherwise.
The List operators
not in operator
– The ‘not in’ operator is used to check if a value exists in the list
or not.
– Evaluates to true if the element is not present in the list and
false otherwise.
The List operators
“+” Operator
The concatenation operator + is used to
join the list elements.
The List operators
“*” Operator
The multiplication operator “ * “ is used to
replicate the elements in the list.
Index Operator []
• The elements of the list can be accessed by using the index
operator [].
Syntax : variable_name [Index value]
The first element of the list is stored at the 0th index, the second
element of the list is stored at the 1st index, and so on.
Index Operator []
Negative indexing
• Python provides us the flexibility to use the negative indexing
also.
• The negative indices are counted from the right.
• The last element (right most) of the list has the index -1, its
adjacent left element is present at the index -2 and so on until the
left most element is encountered.
negative indexing

list[-1] is similar to list[-1+len(list))]list[(-1+12)]list[11] o/p: 11


list[-6] is similar to list[-6+len(list))]list[(-6+12)]list[6] o/p: 6
list[-10] is similar to list[-10+len(list))]list[(-10+12)]list[2] o/p: 2
LIST SLICING [START : END]
• The slicing operator returns a subset of a list , called slice by specifying two
indices , i.e. start and end.
Syntax: variable_name [start index : end index]
• The slice is a sublist from index start to index end – 1.
• If start >= end, list[start : end] returns an empty list. If end specifies a position
beyond the end of the list, Python will use the length of the list for end instead.
LIST SLICING [START : END: STEP SIZE]
Syntax: variable_name[start index : end index: Step Size]
• Start index = where to begin (inclusive)
• Stop index = where to end (exclusive)
• step size= how much to skip each time
• If step is positive, it moves left ➔ right.
• If step is negative, it moves right ➔ left.
COMPARING LIST
• By using comparison operators (>, >=, <=, ==, and !=) we can
compare lists
• Two lists must contain the same type of elements.
• The comparison uses lexicographical ordering.
• The first two elements are compared, and if they differ this deter
mines the outcome of the comparison; if they are equal, the next
two elements are compared, and so on, until either list is
exhausted.
COMPARING LIST
Traversing Elements in a for Loop
• The elements in a Python list are iterable.
• Python supports a convenient for loop, which enables you to
traverse the list sequentially without using an index variable.
The following code displays all the elements in the list myList:
for u in myList:
print(u)
Note: “For each element u in myList, print it.”
The following code displays the elements at odd numbered
positions.

for i in range(0, len(myList), 2):


print(myList[i])
The common operations for sequences

29
List Comprehension

•List comprehensions provide a concise way to create items


from sequence
• A list comprehension consists of brackets containing an
expression followed by a for clause, then zero or more for
or if clauses.
•The result will be a list resulting from evaluating the
expression.

30
List Comprehension

>>> list1 = [x for x range(0, 5)] # Returns a list of 0, 1, 2, 4


>>> list1
[0, 1, 2, 3, 4]
>>> list2 = [0.5 * x for x in list1]
>>> list2
[0.0, 0.5, 1.0, 1.5, 2.0]
>>> list3 = [x for x in list2 if x < 1.5]
>>> list3
[0.0, 0.5, 1.0]

31
Explanation
• In line 1, list1 is created from an expression
using a for clause.
• The numbers in list1 are 0, 1, 2, 3, and 4.
• Each number in list2 is half of the
corresponding number in list1 (line 5).
• In line 9, list3 consists of the numbers whose
value is less than 1.5 in list2
List Methods:Append, insert, remove

['apple', 'banana', 'cherry', 'orange']

['apple', 'orange', 'banana', 'cherry']

['apple', 'cherry']

33
List Methods: Pop, clear, del

['apple', 'banana']

[]

['banana', 'cherry']

34
Splitting a String into a List
• The str class contains the split method, which is useful for splitting items
in a string into a list.
For example, the following statement:
items = "Jane John Peter Susan".split()
splits the string Jane John Peter Susan into the list
['Jane', 'John', 'Peter', 'Susan']
In this case the items are delimited by spaces in the string. You can use a
non space delimiter.
For example, the following statement:
items = "09/20/2012".split("/")
splits the string 09/20/2012 into the list ['09', '20', '2012'].
Lists are Mutable
• Unlike strings, lists are mutable. This means we can change an item in a list
by accessing it directly as part of the assignment statement.
• Using the indexing operator (square brackets) on the left side of an
assignment, we can update one of the list items.
Contd..
• An assignment to an element of a list is called item assignment. Item
assignment does not work for strings because strings are immutable.
• By combining assignment with the slice operator we can update several
elements at once.

• We can also remove elements from a list by assigning the empty list to
them.
some examples that use the append, count, extend, index, and insert
methods:
some examples that use the insert, pop, remove, reverse, and sort
methods:
Contd..

•The word mutator means that the list is changed by the method but nothing is returned
(actually None is returned).
•A hybrid method is one that not only changes the list but also returns a value as its result
Inputting Lists
• The data can be read from console into a list.
• So that we need to enter one data item per line and append it to a
list in a loop.
For example, the following code reads ten numbers one per line
into a list
list=[]
print("enter 10 integers")
for i in range(10):
list.append(eval(input("enter Integers:")))
print(list)
Inputting Lists
• It is more convenient to enter the data in one line separated by
spaces.
• To extract data from single input line we can use split() method
For example, the following code reads ten numbers separated by
spaces from one line into a list:
s=input('enter 10 number')
items=s.split(",")
list=[eval(x) for x in items]

• Invoking input() reads a string.


• Using s.split(“,”) extracts the items delimited by comma from string
s and returns items in a list.
•The last line creates a list of numbers by converting the items into
numbers.
Shifting Lists
• If we want to shift the elements left or right.
• Python does not provide such a method in the list class, but you
can write the following function to perform a left shift.
Copying Lists
Often, in a program, you need to duplicate a list or a part of a list. In such
cases you could attempt to use the assignment statement (=), as follows:
list2 = list1;

•You cannot copy a list simply by typing list2 = list1, because: list2 will
only be a reference to list1, and changes made in list1 will automatically
also be made in list2 46
Copying Lists

To get a duplicate copy of list1 into list2, we can use:


list2 = [x for x in list1]
or
simply:
list2 = [] + list1
Aliasing

• Since variables refer to objects, if we assign one variable to


another, both variables refer to the same object:
example
Line 4 and 5

Line 1
and2

Line:7
Output:
True
False
True Line 8 and 9
True
[5, 82, 83]
Cloning Lists

• If we want to modify a list and also keep a copy


of the original, we need to be able to make a
copy of the list itself, not just the reference.
• This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
• The easiest way to clone a list is to use the slice
operator.
• Taking any slice of a creates a new list. In this
case the slice happens to consist of the whole
list.
example
slice

o/p:[81, 82, 83]


o/p:[5, 82, 83]
Passing Lists to Functions

• When passing a list to a function, the contents of the list may


change after the function call, since a list is a mutable object.
•Since list is an object, passing a list to a function is just like
passing an object to a function.
• For example, the following function displays the elements in a
list:
def printList(lst):
for element in lst:
print(element)
Passing Lists to Functios
def printList(lst):
for element in lst:
print(element)

Invoke the function

lst = [3, 1, 2, 6, 4, 2]
printList(lst)

Invoke the function


printList([3, 1, 2, 6, 4, 2])

Anonymous list

53
Pass By Value
• Python uses pass-by-value to pass arguments to
a function.
• There are important differences between passing
the values of variables of numbers and strings
and passing lists.
– Immutable objects
– Changeable objects

54
Pass By Value (Immutable objects)
• For an argument of a number or a string, the
original value of the number and string outside
the function is not changed,
• because numbers and strings are immutable in
Python.

55
Pass By Value (changeable objects)
• For an argument of a list, the value of the
argument is a reference to a list;
• this reference value is passed to the function.
• Semantically, it can be best described as pass-by-
sharing, i.e., the list in the function is the same as
the list being passed.
• So if you change the list in the function, you will
see the change outside the function.

56
PassListArgument.py
Contd…
O/p:

• We can observe that after m is invoked (line 5, x remains 1,


but y[0] is changed to 5555.
• This is because y and numbers refer to the same list object.
• When m(x, y) is invoked, the reference values of x and y are
passed to number and numbers.
• Since y contains the reference value to the list, numbers now
contains the same reference value to the same list.
• Since number is immutable, altering it inside a function
creates a new instance and the original instance outside the
function is not changed.
• So, outside of the function, x is still 1.
DefualtListArgument.py
Contd… This default value is created only once
[1]
O/p: [1, 2]
[10, 11, 12, 13, 3]
[1, 2, 4]

• The function add appends x to list if x is not in the list (lines 1–5). When the
function is executed for the first time (line 8), the default value [] for the
argument lst is created.
• add(1) adds 1 to list. When the function is called again (line 11), list is now
[1] not [], because list is created only once.
• After add(2) is executed, list becomes [1, 2]. In line 14, the list argument
[11, 12, 13, 14] is given, and this list is passed to list.
• In line 17, the default list argument is used. Since the default list now is [1,
2], after invoking add(4), the default list becomes [1, 2, 4].
DefualtNoneListArgument.py
Contd…
[1]
O/p:
[2]
[10, 11, 12, 13, 3]
[4]

• Here a new empty list is created every time the add function is called
without a list argument (line 3).
• If the list argument is given when invoking the function, the default list is
not used.
Returning a List from a Function
• When a function returns a list, the list’s reference value is returned.
Returning a List from a Function

• In the above program reverse function first creates empty list

• For each element i in list, it inserts i at the beginning (index 0) of

result.

• As it is inserting every time at index 0 , current elements will shift

to next index position

• So at last element in list will be inserted at index 0

• Final obtained list is reverse of original list.


Searching Lists

•Searching is the process of looking for a specific element in a list


•Searching is a common task in computer programming.
• There are many algorithms and data structures devoted to
searching.
•In this section, two commonly used approaches are discussed,
linear search and binary search.
Linear Search
The linear search approach compares the key element,
key, sequentially with each element in list. The method
continues to do so until the key matches an element in
the list or the list is exhausted without a match being
found. If a match is made, the linear search returns the
index of the element in the list that matches the key. If
no match is found, the search returns -1.

66
Linear Search
Key List

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
67
Linear Search
Binary Search
For binary search to work, the elements in the list
must already be ordered. Without loss of generality,
assume that the list is in ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79

The binary search first compares the key with the


element in the middle of the list.

69
Binary Search
Consider the following three cases:

• If the key is less than the middle element, you only need
to search the key in the first half of the list.
• If the key is equal to the middle element, the search
ends with a match.
• If the key is greater than the middle element, you only
need to search the key in the second half of the list.
70
Binary Search

Key List

8 1 2 3 4 6 7 8 9

8 1 2 3 4 6 7 8 9

8 1 2 3 4 6 7 8 9

71
Binary Search

72
Binary Search
# Use binary search to find the key in the list
def binarySearch(lst, key):
low = 0
high = len(lst) - 1

while high >= low:


mid = (low + high) // 2
if key < lst[mid]:
high = mid - 1
elif key == lst[mid]:
return mid
else:
low = mid + 1

return -low - 1 # Now high < low, key not


found
Binary Search

The binarySearch method returns the index of the


element in the list that matches the search key if it
is contained in the list. Otherwise, it returns

- insertion point - 1.

The insertion point is the point at which the key


would be inserted into the list.

74
Chapter-2
Tuples, Sets, and Dictionaries
Introducton

• Tuples are used for storing a fixed list of elements


• A set for storing and quickly accessing nonduplicate
elements
• A dictionary for storing key/value pairs and for
accessing elements quickly using the keys.
Motivations
The No Fly List is a list, created and maintained by the
United States government's Terrorist Screening Center, of
people who are not permitted to board a commercial
aircraft for travel in or out of the United States. Suppose
we need to write a program that checks whether a person
is in the No Fly List. You can use a Python list to store the
persons in the No Fly List. However, a more efficient data
structure for this application is a set. 77
Tuples
Tuples are like lists, but their elements are fixed; that is,
once a tuple is created, you cannot add new elements,
delete elements, replace elements, or reorder the
elements in the tuple.

If the contents of a list in your application do not change,


you should use a tuple to prevent data from being
modified accidentally. Furthermore, tuples are more
efficient than lists.
Creating Tuples

You create a tuple by enclosing its elements inside a pair of parentheses.


The elements are separated by commas. You can create an empty tuple
and create a tuple from a list, as shown in the following example:

t1 = () # Create an empty tuple

t2 = (1, 3, 5) # Create a set with three elements

# Create a tuple from a list


t3 = tuple([2 * x for x in range(1, 5)])

You can also create a tuple from a string. Each character in the string
becomes an element in the tuple. For example:
# Create a tuple from a string
t4 = tuple("abac") # t4 is ['a', 'b', 'a', 'c']
Inbuilt functions for tuple
• len(tuple):It calculates the length of the tuple.
Inbuilt functions for tuple
• max(tuple) :It returns the maximum element
of the tuple.
Inbuilt functions for tuple
• min(tuple) :It returns the minimum element of
the tuple.
Inbuilt functions for tuple
• Sum() : Returns the sum of all the elements in
the tuple
Inbuilt functions for tuple
• index(x): Returns the index of the element x
Inbuilt functions for tuple
• count(x) : Returns the number of occurrences
of element x
Indexing and slicing
• Tuples are like lists , so indexing and slicing of
tuple is similar to that of lists.
• The indexing operator “[ ]” is uses to access
elements of a tuple.
• The index must be an integer; so we cannot use
float or other types. This will result in “type error”.
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the
second last item and so on.
Example
Operations on tuples
• Operators can be used to concatenate or
multiply tuples.
• Concatenation is done with the ”+” operator
• Multiplication is done with the ”*” operator.
Concatenation(using “+” operator)
Repetition operator
• “*” : The multiplication operator is used to
replicate the elements of the tuple.
Passing variable length arguments to tuples

• The special syntax ”*args” in function definitions in


python is used to pass a variable number of arguments
to a function
• syntax to create a function that can take variable
length arguments.
def function_name(*args) :
#
# body of the function
#
• *args: holds variable length arguments.
Finding the sum of the given tuple using *
args
List to tuples
• A tuple can also be created from a list.
Soring tuples
• A tuple does not contains any method named
sort.
• In order to sort a tuple, first convert a tuple in
to a list, after conversion use sort() method for
lists and again convert it into a tuple.
Soring tuples
Traverse tuples from a list
• A tuple assignment can be used in the for loop
to traverse a list of tuple.
zip() function in python
• The zip() is an inbuilt function in python.
• The zip() function takes items in a sequence
from a number of collections(list, tuple, set ,
etc …) and aggregates them in a tuple, and
return it.
Zip() example
Zip() example
• If the sequences are not of the same length
then the result of the zip() function has the
length of the shorter sequence.
Inverse zip(*) function
• The * operator is used with in the zip()
function.
• The * operator unpacks a sequence into
positional arguments.
Sets

Sets are like lists to store a collection of items.


Unlike lists, the elements in a set are unique and
are not placed in any particular ordered. If your
application does not care about the order of the
elements, using a set to store elements is more
efficient than using lists. The syntax for sets is
braces {}.
104
Creating Sets
s1 = set() # Create an empty set

s2 = {1, 3, 5} # Create a set with three elements

s3 = set([1, 3, 5]) # Create a set from a tuple

# Create a set from a list


s4 = set([x * 2 for x in range(1, 10)])

# Create a set from a string


s5 = set("abac") # s5 is {'a', 'b', 'c'}

105
Contd…
• A set can contain the elements of the same type or mixed
types.
• For example, s = {1, 2, 3, "one", "two", "three"} is a set that
contains numbers and strings.
• Each element in a set must be hashable.
• Each object in Python has a hash value and an object is
hashable i.e., hash value never changes during its lifetime.
• Sets use hashing to store and retrieve elements efficiently.
• Internally, each element’s hash is used to determine where to
store it in memory 106
Manipulating and Accessing Sets

• add():Add() method is used for adding element to sets


Syntax: set_name.add(element)
• remove():remove() method is used for removing elements
Syntax: set_name.remove(element)
• len(): For finding len of set
• min(): finds min element in set
• max():finds max element in set
• sum(): finds sum of all elements in list
• for loop to traverse all elements in a set.
• in or not in operator to determine whether an element is in the
set. 107
Manipulating and Accessing Sets
>>> s1 = {1, 2, 4}
>>> s1.add(6)
>>> s1
{1, 2, 4, 6}
>>> len(s1)
4
>>> max(s1)
6
>>> min(s1)
1
>>> sum(s1)
13
>>> 3 in s1
False
>>> s1.remove(4)
>>> s1
{1, 2, 6}
>>>
108
Subset and Superset
• A set s1 is a subset of s2 if every element in s1 is also in s2.
syntax: s1.issubset(s2)
It determines whether s1 is a subset of s2
###subset
>>> s1 = {1, 2, 4}
>>> s2 = {1, 4, 5, 2, 6}
>>> s1.issubset(s2) # s1 is a subset of s2
True
>>>
• A set s1 is a superset of set s2 if every element in s2 is also in s1.
Syntax: s1. issuperset(s2)
It determines whether s1 is a superset of s2
###Superset
>>> s1 = {1, 2, 4}
>>> s2 = {1, 4, 5, 2, 6}
>>> s2.issuperset(s1) # s2 is a superset of s1
True
109
>>>
Equality Test

The == and != operators to test if two sets contain


the same elements.

>>> s1 = {1, 2, 4}
>>> s2 = {1, 4, 2}
>>> s1 == s2
True
>>> s1 != s2
False
>>>
110
Comparison Operators
Note that it makes no sense to compare the sets using the
conventional comparison operators (>, >=, <=, <), because the
elements in a set are not ordered. However, these operators have
special meaning when used for sets.

s1 > s2 returns true is s1 is a proper superset of s2.


(i.e., s1 has one extra element )

s1 >= s2 returns true is s1 is a superset of s2.

s1 < s2 returns true is s1 is a proper subset of s2.


(i.e., s2 has one extra element )

s1 <= s2 returns true is s1 is a subset of s2.


111
Comparison Operators
s1 = {1, 2}
s2 = {1, 2, 3}

print(s1 < s2) # True (s1 is a proper subset)


print(s1 <= s2) # True (s1 is a subset)

print(s2 > s1) # True (s2 is a proper superset)


print(s2 >= s1) # True (s2 is a superset)

print(s1 == s2) # False

112
Set Operations
Python provides the methods for performing
set union, intersection, difference, and
symmetric difference operations.
Set Operation-- (union, |)
•The union of two sets is a set that contains all the elements from
both sets.
•we can use the union method or the | operator to perform this
operation.
For example:
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.union(s2)
{1, 2, 3, 4, 5}
>>>
>>> s1 | s2
{1, 2, 3, 4, 5}
>>>
114
Set Operation --(intersection, &)
•The intersection of two sets is a set that contains the elements that
appear in both sets.
• we can use the intersection method or the & operator to perform
this operation.
For example:
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.intersection(s2)
{1}
>>>
>>> s1 & s2
{1}
115
>>>
Set Operation (difference, -)
•The difference between set1 and set2 is a set that contains the
elements in set1 but not in set2.
•we can use the difference method or the - operator to perform
this operation.
•For example:

>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.difference(s2)
{2, 4}
>>>
>>> s1 - s2
{2, 4}
>>>
116
Set Operations (symetric_difference, ^)
•The symmetric difference (or exclusive or) of two sets is a set that
contains the elements in either set, but not in both sets.
• we can use the symmetric_difference method or the ^ operator to
perform this operation.
•For example:
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.symmetric_difference(s2)
{2, 3, 4, 5}
>>>
>>> s1 ^ s2
{2, 3, 4, 5}
>>> 117
Comparing the Performance of Sets and
Lists

Sets are more efficient than lists for the in and


not in operator and for the remove method.
Dictionary
A dictionary is a container object that stores a
collection of key/value pairs. It enables fast
retrieval, deletion, and updating of the value by
using the key
Dictionary
Why dictionary?

• Suppose a program needs to store the detailed information on


terrorists in the “No-Fly” list.

• A dictionary is an efficient data structure for such a task.

• A dictionary is a collection that stores the values along with the


keys.

• The keys are like an index operator. In a list, the indexes are
integers. In a dictionary, the key must be a hashable object.
120
Dictionary
A dictionary cannot contain duplicate keys. Each key maps to one value.
A key and its corresponding value form an item (or entry) stored in a
dictionary. The data structure is a called a “dictionary” because it
resembles a word dictionary, where the words are the keys and the
words’ definitions are the values. A dictionary is also known as a map,
which maps each key to a value

121
Creating a Dictionary
To create a dictionary by enclosing the items inside a pair of curly
braces ({}). Each item consists of a key, followed by a colon, followed
by a value. The items are separated by commas. For example, the
following statement:
dictionary = {} # Create an empty dictionary
students = {"111-34-3434":"John", "132-56-6290":"Peter"}
Above example creates a dictionary with two items. The item is in
the form key:value. The key in the first item is 111-34-3434, and its
corresponding value is John. The key must be of a hashable type
such as numbers and strings. The value can be of any type.
122
Adding/Modifying Entries/Retrieving values

To add an entry to a dictionary, use


dictionary[key] = value

For example,
dictionary["susan"] = 50

If the key is already in the dictionary, the preceding


statement replaces the value for the key

123
Adding/Modifying Entries/Retrieving values
To retrieve a value
Syntax: dictionaryName[key]
If the key is in the dictionary, the value for the key is returned.
Otherwise, a KeyError exception is raised

124
Deleting Entries
To delete an entry from a dictionary

Syntax: del dictionary[key]

For example: del students["234-56-9010"]


This statement deletes an item with the key 234-56-9010 from the
dictionary. If the key is not in the dictionary, a KeyError exception is
raised.

125
Looping Entries
You can use a for loop to traverse all keys in the dictionary.
Syntax:
for key in dictionary:
print(str(key )+ ":" + str(dictionary[key]))
Looping Entries
The len operator

len(dictionary) returns the number of the elements in the


dictionary.

Len(dict) return number of items in dictionary

128
Testing Whether a Key Is in a Dictionary

By using the in or not in operator we can determine whether a key


is in the dictionary or not

>>> dictionary = {“ram":40, “Ravi":45}


>>> “ram" in dictionary
True
>>> “hari" in dictionary
False

129
Equality Test

By using == and != operators we can to test whether two


dictionaries contain the same items

In this example, d1 and d2 contain the same items regardless


of the order of the items in a dictionary.

130
The Dictionary Methods

dict
keys(): tuple Returns a sequence of keys.
values(): tuple Returns a sequence of values.
items(): tuple Returns a sequence of tuples (key, value).
clear(): void Deletes all entries.
get(key): value Returns the value for the key.
pop(key): value Removes the entry for the key and returns its value.
popitem(): tuple Returns a randomly-selected key/value pair as a tuple and
removes the selected entry.

131
The Dictionary Methods

132

You might also like