You are on page 1of 106

Unit III – Data Structures in

Python
{ Presenter : Mr. C P Bhamare
Python Lists

• The important characteristics of Python lists are as follows:


1. Lists are ordered.
2. Lists can contain any arbitrary objects.
3. List elements can be accessed by index.
4. Lists can be nested.
5. Lists are mutable.
6. Lists are dynamic.
Creating a List

• List is created by placing all the elements inside square brackets [], separated by commas.
• It can have any number of items and they may be of different types (integer, float, string
etc.).

# empty list
my_list = [ ]

# list of integers
my_list = [1, 2, 3]

# list with mixed data types


my_list = [1, "Hello", 3.4]
Creating a List

• A list can also have another list as an item. This is called a nested list.

# nested list
my_list = [“Hello", [8, 4, 6], ['a']]
Adding Elements to a List

• We can add one item to a list using the append() method or add several
items using extend() method.
• These methods add the elements at the end of the list.

# Appending and Extending lists in Python


my_list = [1,2,3,4,5]
my_list.append(10)
print(my_list) # output : [1,2,3,4,5,10]

my_list.extend([11, 16,18])
print(my_list) # output : [1,2,3,4,5,10,11,16,18]
Adding Elements to a List

• We can insert one item at a desired location by using the method insert()
• We can insert multiple items by squeezing it into an empty slice of a list.

# Demonstration of list insert() method


my_list = [1,2,3,4,5]
my_list.insert(2,10)
print(my_list) # output : [1,2,10,3,4,5]

my_list[3:3] = [15,16,17]
print(my_list) # output : [1,2,10,15,16,17,3,4,5]
Accessing elements from the List

• We can use the index operator [] to access an item in a list. In Python, indices
start at 0. So, a list having 5 elements will have an index from 0 to 4.

# List indexing
my_list = [1, 2, ’Hello’, 3.4, 5]
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: Hello
print(my_list[4]) # Output: 5
print(my_list[4.0]) # error
Accessing elements from the List

• Nested lists are accessed using nested indexing.

# Nested List
my_list = ["Hello", [2, 0, 1, 5]]

# Nested indexing
print(my_list[0][1]) #ouput : e
print(my_list[1][3]) #ouput : 5
Accessing elements from the List

• 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.

# Negative indexing in lists


my_list = [‘P',‘Y',‘T',‘H',‘O‘,’N’]

print(my_list[-1]) #output : N
print(my_list[-5]) #output : Y
Accessing elements from the List

• We can access a range of items in a list by using the slicing operator :(colon).

# List slicing in Python


my_list = [1, ‘H’, 3.4, ‘O’, ‘Welcome’]

# elements 2nd to 4th


print(my_list[1:4]) # output : [‘H’, 3.4, ‘O’]
print(my_list[:-5]) # output : [ ]
print(my_list[:-3]) # output : [1,’H’ ]
# elements beginning to end
print(my_list[:]) # output : [1, ‘H’, 3.4, ‘O’, ‘Welcome’]
print(my_list[-1:-3 :-1] # output : [‘Welcome’,’O’]
Removing/Deleting elements from the List

• We can delete one or more items from a list using the keyword del. It can
even delete the list entirely.
# Deleting list elements
my_list = [1, ‘H’, 3.4, ‘O’, ‘Welcome’]

del my_list[1]
print(my_list) # output : [1, 3.4, ‘O’,’Welcome’]

del my_list[1:4]
print(my_list) # output : [1]
Removing/Deleting elements from the List

# Deleting entire list


my_list = [1, ‘H’, 3.4, ‘O’, ‘Welcome’]

# delete entire list


del my_list
print(my_list) # output : Error: name my_list not defined
Removing/Deleting elements from the List

• We can use remove() method to remove the given item or pop() method to
remove an item at the given index.

# Deleting list elements


my_list = [1, ‘H’, 3.4, ‘O’, ‘Welcome’]

my_list.remove( ‘H’)
print(my_list) # output : [1, 3.4, ‘O’, ’Welcome’]

my_list.pop(1 )
print(my_list) # output : [1, ‘O’, ’Welcome’]
Removing/Deleting elements from the List

• The pop() method removes and returns the last item if the index is not
provided. This helps us implement lists as stacks (first in, last out data
structure).

# Deleting list elements


my_list = [1, ‘H’, 3.4, ‘O’, ‘Welcome’]

my_list.pop( )
print(my_list) # output : [1, ‘H’, 3.4, ‘O’]
Removing/Deleting elements from the List

• We can also use the clear() method to remove all the elements from a list.

# Deleting list elements


my_list = [1, ‘H’, 3.4, ‘O’, ‘Welcome’]

my_list.clear( )
print(my_list) # output : [ ]
Update/Change List Elements

• Lists are mutable, meaning their elements can be changed unlike string or tuple.
• We can use the assignment operator = to change an item or a range of items.

# Correcting values in a list


my_list = [2, 4, 6, 8]

# change the 1st item


my_list[0] = 1
print(my_list) # output : [1,4,6,8]

# change 2nd to 4th items


my_list[1:4] = [3, 5, 7]
print(my_list) # output : [1,3,5,7]
Basic List Operations

Python Expression Results Description

len([1, 2, 3]) 3 Length


[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

[1,2] * 4 [1,2,1,2,1,2,1,2] Repetition

3 in [1, 2, 3] True Membership


1
for x in [1, 2, 3]:
2 Iteration
print(x)
3
Basic List Operations

Python Expression Results Description

len([1, 2, 3]) 3 Length


[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

[1,2] * 4 [1,2,1,2,1,2,1,2] Repetition

3 in [1, 2, 3] True Membership


1
for x in [1, 2, 3]:
2 Iteration
print(x)
3
Basic List Operations

• We can use + operator to combine two lists. This is also called concatenation.
• The * operator repeats a list for the given number of times.

# Concatenating and repeating lists


my_list = [1, 2, 3]
print(my_list + [4, 5, 6]) # output : [1, 2, 3, 4, 5, 6]

print([10,11,12] * 3) # output : [10,11,12, 10,11,12, 10,11,12]


Basic List Operations

• We can test if an item exists in a list or not, using the membership operator in and not in.

# Concatenating and repeating lists


my_list = [1, 2, 3]
print( 3 in my_list) # output : True
print( 2 not in my_list) # output : False
Basic List Operations

• Using a for loop we can iterate through each item in a list.

Output :
my_list = [1, 2, 3]
1
for x in my_list :
2
print(x)
3
Basic List Operations

• To find the number of elements in a list, us the function len .

my_list = [1, 2, 3]
print( len(my_list)) # output : 3
Python List Methods

Python List Methods


append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of the number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
Python List Methods

# Python list methods


my_list = [3, 8, 1, 6, 0, 8, 4]
print(my_list.index(8)) # Output: 1
print(my_list.count(8)) # Output: 2
my_list.sort()
print(my_list) # Output: [0, 1, 3, 4, 6, 8, 8]
my_list.reverse()
print(my_list) # Output: [8, 8, 6, 4, 3, 1, 0]
Python List Functions

Function with Description

cmp(list1, list2) - Compares elements of both lists.

len(list) - Gives the total length of the list.

max(list) - Returns item from the list with max value.

min(list) - Returns item from the list with min value.

list(seq) - Converts a tuple into list.


List Comprehension

• List comprehensions are used for creating new lists from other iterables like tuples,
strings, lists, etc.
• A list comprehension consists of an expression followed by for statement inside square
brackets.

# below list contains square of all numbers from range 1 to 5

square = [x ** 2 for x in range(1, 6)]


print (square) # output :[1, 4, 9, 16, 25]

# This code is equivalent to:


square = [ ]
for x in range(1,6):
square.append(x** 2)
print(square) # output :[1, 4, 9, 16, 25]
List Comprehension

• A list comprehension can optionally contain more for or if statements. An optional if


statement can filter out items for the new list.

# below list contains square of all odd numbers from range 1 to 10


odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print (odd_square) #output : [1, 9, 25, 49, 81]

# for understanding, above generation is same as,


odd_square = []
for x in range(1, 11):
if x % 2 == 1:
odd_square.append(x**2)
print (odd_square) #output : [1, 9, 25, 49, 81]
Python Tuple

• A tuple in Python is similar to a list. The difference between the two is that we cannot
change the elements of a tuple once it is assigned whereas we can change the elements of
a list.
• The important characteristics of Python Tuples are as follows:
1. Tuples are ordered.
2. Tuples can contain any arbitrary objects.
3. Tuples elements can be accessed by index.
4. Tuples can be nested.
5. Tuples are immutable.
Creating a Tuple

• A tuple is created by placing all the items (elements) inside parentheses ( ), separated by
commas. The parentheses are optional, however, it is a good practice to use them.
• A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).

# Empty tuple
my_tuple = ()
print(my_tuple) #output:( )

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple) #output:( 1, 2, 3)
Creating a Tuple

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4, “Welcome”)
print(my_tuple) #output:(1, "Hello", 3.4, “Welcome”)

#Creating a Tuple with nested tuples


Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', ‘hello')
Tuple3 = (Tuple1, Tuple2)
print(Tuple3) #output:((0, 1, 2, 3), ('python', ‘hello'))
Creating a Tuple

# nested tuple
my_tuple = (“Hello", [8, 4, 6], (1, 2, 3))
print(my_tuple) # output : (‘Hello', [8, 4, 6], (1, 2, 3))

#Creating a Tuple with the use of built-in function


Tuple1 = tuple(‘python')
print(Tuple1) # output : (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
Creating a Tuple

• A tuple can also be created without using parentheses. This is known as tuple packing.
• The individual items are “unpacked” into the objects in the tuple. When unpacking, the
number of variables on the left must match the number of values in the tuple.

my_tuple = 3, 4.6, “python"


print(my_tuple) #output : (3, 4.6, ‘python')

# tuple unpacking is also possible


a, b, c = my_tuple
print(a) #3
print(b) # 4.6
print(c) # python
Creating a Tuple

• Creating a tuple with one element is a bit tricky. Having one element within parentheses is
not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.

my_tuple = ("hello")
print(type(my_tuple)) # output : <class 'str'>

# Creating a tuple having one element


my_tuple = ("hello",)
print(type(my_tuple)) # output : <class 'tuple'>

# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # output:<class 'tuple'>
Accessing elements from the Tuple

• We can use the index operator [] to access an item in a Tuple. In Python,


indices start at 0. So, a tuple having 5 elements will have an index from 0 to 4.

# Tuple indexing
my_tuple = (1, 2, ’Hello’, 3.4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: Hello
print(my_tuple[4]) # Output: 5
print(my_tuple[4.0]) # error
print(my_tuple[6]) # IndexError: tuple index out of range
Accessing elements from the Tuple

• 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.

# Negative indexing in tuple


my_tuple = (‘P',‘Y',‘T',‘H',‘O‘,’N’)

print(my_tuple[-1]) #output : N
print(my_tuple[-5]) #output : Y
Accessing elements from the Tuple

• We can access a range of items in a tuple by using the slicing operator :(colon).

# Tuple slicing in Python


my_tuple = (1, ‘H’, 3.4, ‘O’, ‘Welcome’)
# elements 2nd to 4th
print(my_tuple[1:4]) # output : (‘H’, 3.4, ‘O’)
print(my_tuple[:-5]) # output : ( )
print(my_tuple[:-3]) # output : (1,’H’ )
# elements beginning to end
print(my_tuple[:]) # output : (1, ‘H’, 3.4, ‘O’, ‘Welcome’)
print(my_tuple[::-1]) # output : ('Welcome', 'O', 3.4, 'H', 1)
print(my_tuple[-1:-3 :-1] # output : (‘Welcome’,’O’)
Deleting a Tuple

• Tuples are immutable and hence they do not allow deletion of a part of it.

# Deleting entire tuple


Tuple1 = (0, 1, 2, 3, 4)
# can't delete items
del my_tuple[3] # output : TypeError: 'tuple' object doesn't support item deletion
Deleting a Tuple

• The entire tuple gets deleted by the use of del keyword.

# Deleting entire tuple


Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print(Tuple1) # output : Error: name Tuple1 not defined
Changing a Tuple

• Unlike lists, tuples are immutable.


• This means that elements of a tuple cannot be changed once they have been
assigned. But, if the element is itself a mutable data type like a list, its nested items
can be changed.
• We can also assign a tuple to different values (reassignment).
Changing a Tuple

# Changing tuple values


my_tuple = (4, 2, 3, [6, 5])
my_tuple[1] = 9 # TypeError: 'tuple' object does not support item assignment

# Changing tuple values


my_tuple = (4, 2, 3, [6, 5])
# However, item of mutable element can be changed
my_tuple[3][0] = 9
print(my_tuple) # Output: (4, 2, 3, [9, 5])

my_tuple = (1, 2, 3, 4, 5) # Tuples can be reassigned


print(my_tuple) # Output: (1, 2, 3, 4, 5)
Basic Tuple Operations

• We can use + operator to combine two tuples. This is called concatenation.


• We can also repeat the elements in a tuple for a given number of times using
the * operator. Both + and * operations result in a new tuple.

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
(1,2) * 4 (1,2,1,2,1,2,1,2) Repetition
3 in (1, 2, 3) True Membership
1
for x in (1, 2, 3):
2 Iteration
print(x)
3
Tuple Methods

• Methods that add items or remove items are not available with tuple. Only the
following two methods are available.

Built-in-Method Description

find in the tuple and returns the index of the


index( )
given value where it’s available

returns the frequency of occurrence of a


count( )
specified value
Tuple Methods

my_tuple1 = ('a', 'p', 'p', 'l', 'e')


print(my_tuple1.count('p')) # Output: 2
print(my_tuple1.index('l')) # Output: 3

my_tuple2 = (0,1,2,3,4,1,9,1,10)
print(my_tuple2.count(1)) # Output: 3
print(my_tuple2.index(9)) # Output: 6
Python Tuple Functions

Function with Description

cmp(tuple1, tuple2) - Compares elements of both tuples.

len(tuple) - Gives the total length of the tuple.

max(tuple) - Returns item from the tuple with max value.

min(tuple) - Returns item from the tuple with min value.

list(seq) - Converts a tuple into list.

sum(tuple ) - Sums up the numbers in the tuple


Python Tuple

In Python, the swap can be done with a single tuple assignment:

a = 10
b = 20
print(f‘ Before swapping a : {a} , b : {b}’)

a, b = b, a
print(f‘ After swapping a : {a} , b : {b}’)
Advantages of Tuple over List

• We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than with list. So there is
a slight performance boost.
• Tuples that contain immutable elements can be used as a key for a dictionary. With
lists, this is not possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected. Using a tuple instead of a list guards data against accidental
modification.
Set in Python

• A set is an unordered collection of elements.


• Every set element is unique (no duplicates) and must be immutable (cannot be
changed).
• However, a set itself is mutable. We can add or remove items from it.
• Sets can also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.
Creating a Set

• A set is created by placing all the items (elements) inside curly braces { }, separated by
comma, or by using the built-in set() function.
• It can have any number of items and they may be of different types (integer, float, tuple,
string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its
elements.
Creating a Set

• Creating an empty set is a bit tricky.


• Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements, we use the set() function without any argument.

# Distinguish set and dictionary while creating empty set


my_set = { }
print(type(my_set)) #output: <class 'dict'>

# initialize a with set()


my_set = set()
print(type(my_set)) #output: <class ‘set'>
print(my_set) #output: set( )
Creating a Set

# Creating a Set with the use of a String


set1 = set(“Hello")
print(set1) #output: {'l', 'e', 'o', 'H'}

# Creating a Set with the use of a List


set1 = set([“Hello", “Welcome", 4.0, 10])
print(set1) #output: {4.0, 10, 'Hello', 'Welcome'}

Note : We can see that the resulting sets are unordered: the original order, as specified in the
definition, is not necessarily preserved. Additionally, duplicate values are only represented in
the set once.
Creating a Set

# set of integers
my_set = {1, 2, 3, 4}
print(my_set) #output: {1, 2, 3, 4}

# set of mixed datatypes


my_set = {7, 1.0, "Hello", (1, 2, 3)}
print(my_set) #output: {7, 1.0, "Hello", (1, 2, 3)}
Creating a Set

# set cannot have duplicates


my_set = {1, 2, 3, 4, 3, 2}
print(my_set) # Output: {4, 2, 1, 3}

# we can make set from a list


my_set = set([1, 2, 3, 2])
print(my_set) # Output: {1, 3, 2}

# set cannot have mutable items


# here [3, 4] is a mutable list. This will cause an error.
my_set = {1, 2, [3, 4]} #output: error
Accessing a Set

• Set items cannot be accessed by referring to an index, since sets are unordered the items has
no index. But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.

# set of integers
my_set = {1, 2, 3, 4}
for x in my_set :
print(x) #output: 1 2 3 4
Modifying a set in Python

• Sets are mutable. However, since they are unordered, indexing has no meaning.
• We cannot access or change an element of a set using indexing or slicing. Set data type
does not support it.
• Use built-in set functions add(), remove() or update() methods to modify set collection.
Adding Elements to a Set

• We can add a single element to set using the add() method.Loops are used to add multiple
elements at a time with the use of add() method.

my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # output: {1, 2, 3, 4}
# Adding elements to the Set using Iterator
set1 = set( )
for i in range(1, 6) :
set1.add(i)
print(set1) #output : {1, 2, 3, 4, 5}
Adding Elements to a Set

• Multiple elements can be added using the update() method. The update() method can take
tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.

# set of integers
my_set = {1,2,3}
my_set.update([3,4,5])
print(my_set) #output: {1, 2, 3, 4, 5}

# add list and set


my_set1 = {1,2,3}
my_set1.update([4,5],{1,6,9})
print(my_set1) #output: {1, 2, 3, 4, 5, 6, 9}
Removing elements from a set

• A particular item can be removed from a set using the methods discard() and remove().

# initialize my_set
my_set = {1, 2, 3, 4, 5, 6}
my_set.discard(4) # discard an element
print(my_set) #output: {1, 2, 3, 5, 6}

my_set.remove(2) # remove an element


print(my_set) #output: {1, 3, 5, 6}
Removing elements from a set

• The only difference between the two is that the discard() method leaves a set unchanged if
the element is not present in the set. On the other hand, the remove() method will raise an
error in such a condition (if element is not present in the set).

# initialize my_set
my_set = {1, 3, 5}
my_set.discard(2) # discard an element not present in my_set
print(my_set) #output: {1, 3, 5}

my_set.remove(2) # remove an element not present in my_set


print(my_set) #output: KeyError: 2
Removing elements from a set

• pop() method can also be used to remove and return an element from the set, but it
removes only the last element of the set.
• Note – Since set is an unordered data type, there is no way of determining which item
will be popped. It is completely arbitrary.

# initialize set1
set1 = set(“Hello")
print(set1) #output: {'l', 'e', 'o', 'H'}
set1.pop( ) # pop random element
print(my_set) #output: {'e', 'o', 'l'}
Removing elements from a set

• We can also remove all the items from a set using the clear() method.

# initialize set1
set1 = {1,2,3}
set1.clear()
print(set1) #output: set( )
Python Set Operations

• Set data type in Python implements as the set defined in mathematics.


• Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods
• Operators |, &, - and ^ perform union, intersection, difference, and symmetric difference
operations, respectively. Each of these operators has a corresponding method associated
with the built-in set class.
Set Union

• Union: Returns a new set with elements from both the sets.
• Union of A and B is a set of all elements from both sets.
• Union is performed using | operator. Same can be accomplished using the union()
method.
Set Union

# Set union : initialize A and B


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print( A | B ) #output: {1, 2, 3, 4, 5, 6, 7, 8}
Set Union

# Set union : initialize A and B


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use union function


print( A.union(B) ) #output : {1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B


print( B.union(A) ) #output : {1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection

• Intersection: Returns a new set containing elements common to both sets.


• Intersection of A and B is a set of elements that are common in both the sets.
• Intersection is performed using & operator. Same can be accomplished using the
intersection() method.
Set Intersection

# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use & operator


print( A & B ) #output: {4, 5}
Set Intersection

# Set Intersection : initialize A and B


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use intersection function on A


print( A.intersection(B) ) #output : {4, 5}

# use intersection function on B


print( B.intersection(A) ) #output : {4, 5}
Set Difference

• Difference: Returns a set containing elements only in the first set, but not in the second
set.
• Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A.
• Difference is performed using - operator. Same can be accomplished using the difference()
method.
Set Difference

# Difference of two sets


# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use - operator on A
print( A - B ) #output: {1, 2, 3}

# use - operator on B
print( B - A ) #output: {8, 6, 7}
Set Difference

# Set Difference : initialize A and B


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use difference function on A


print( A.difference(B) ) #output : {1, 2, 3}

# use difference function on B


print( B.difference(A) ) #output : {8, 6, 7}
Set Symmetric Difference

• Symmetric Difference: Returns a set consisting of elements in both sets, excluding the
common elements.
• Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding
the intersection).
• Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
Set Symmetric Difference

# Symmetric difference of two sets


# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
print( A ^ B ) #output: {1, 2, 3, 6, 7, 8}
Set Symmetric Difference

# Set Difference : initialize A and B


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use symmetric_difference function on A


print( A.symmetric_difference(B) ) #output : {1, 2, 3, 6, 7, 8}

# use symmetric_difference function on B


print( B.symmetric_difference(A) ) #output : {1, 2, 3, 6, 7, 8}
Basic Set Operations

Python Expression Results Description

len({1, 2, 3}) 3 Length


3 in {1, 2, 3} True Membership
1
for x in {1, 2, 3}:
2 Iteration
print(x)
3
Set Methods

Method Description
add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

Removes an element from the set if it is a member. (Do nothing if the


discard()
element is not in set)

intersection() Returns the intersection of two sets as a new set

intersection_update() Updates the set with the intersection of itself and another
Set Methods

Method Description
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element. Raises KeyError if the set is
pop()
empty

Removes an element from the set. If the element is not a member, raises a
remove()
KeyError

symmetric_difference() Returns the symmetric difference of two sets as a new set

symmetric_difference_update() Updates a set with the symmetric difference of itself and another

union() Returns the union of sets in a new set

update() Updates the set with the union of itself and others
Built-in Functions with Set

Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
Returns an enumerate object. It contains the index and value for all the items of the
enumerate()
set as a pair.
len() Returns the length (the number of items) in the set.

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

sorted() Returns a new sorted list from elements in the set(does not sort the set itself).

sum() Returns the sum of all elements in the set.


Python Frozenset

• Frozenset is a new class that has the characteristics of a set, but its elements cannot be
changed once assigned. While tuples are immutable lists, frozensets are immutable sets.
• Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other
hand, frozensets are hashable and can be used as keys to a dictionary.
• Frozensets can be created using the frozenset() function.
• This data type supports methods like copy(), difference(), intersection(), isdisjoint(),
issubset(), issuperset(), symmetric_difference() and union(). Being immutable, it does not
have methods that add or remove elements.
Python Frozenset

# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

A.isdisjoint(B) #ouput : False


A.difference(B) #output: frozenset({1, 2})
print(A | B) #output: frozenset({1, 2, 3, 4, 5, 6})
A.add(3) #output: AttributeError: 'frozenset' object has no attribute 'add'
Ordered or Unordered?

• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
• When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
• Unordered means that the items does not have a defined order, you cannot refer to an
item by using an index.
Dictionary in Python

• Python dictionary is an ordered collection of items. Each item of a dictionary has a


key/value pair.
• Dictionaries are optimized to retrieve values when the key is known.
• Dictionary is mutable. We can add or remove items from it.
• Dictionary is dynamic. It can grow and shrink as needed.
• It can be nested. A dictionary can contain another dictionary.
• Dictionary elements are accessed via keys.
Creating Python Dictionary

• Creating a dictionary is as simple as placing items inside curly braces {} separated by


commas. we can also create a dictionary using the built-in dict() function.
• An item has a key and a corresponding value that is expressed as a pair (key: value).
• While the values can be of any data type and can be duplicated, keys must be of
immutable type (string, number or tuple with immutable elements) and must be
unique.
Creating a Dictionary

# empty dictionary
my_dict = { }
print(my_dict) #output: { }

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}
print(my_dict) #output: {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict) #output: {'name': 'John', 1: [2, 4, 3]}
Creating a Dictionary

my_dict = dict( )
print(my_dict) #output: { }

# using dict()
my_dict = dict({1:'apple', 2:'ball'})
print(my_dict) #output: {1: 'apple', 2: 'ball'}

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])
print(my_dict) #output: {1: 'apple', 2: 'ball'}
Creating a Dictionary

# Creating a Nested Dictionary


Dict = {
1: ‘Hello’,
2: ‘Good Morning’,
3:{'A' : 'Welcome', 'B' : 'To', 'C' : ‘Python'}
}
print(Dict)
Accessing Elements from Dictionary

• While indexing is used with other data types to access values, a dictionary uses keys.
Keys can be used either inside square brackets [ ] or with the get() method.
• If we use the square brackets [ ], KeyError is raised in case a key is not found in the
dictionary. On the other hand, the get() method returns None if the key is not found.
Accessing Elements from Dictionary

# get vs [] for retrieving elements


my_dict = {'name': 'Jack', 'age': 28}
print(my_dict['name']) # output: Jack
print(my_dict.get('age')) # output: 28

# Trying to access keys which doesn't exist throws error


print(my_dict.get(‘city')) # output : None
print(my_dict[‘city']) #output : KeyError : ‘city’
Accessing Elements from Dictionary

# Accessing element of a nested dictionary


my_dict = {'name': 'Jack', 'age': 27, 'city': 'Mumbai', 'marks': {'phy': 78, 'chem': 90}}
print(my_dict[‘marks'][‘phy’]) # output: 78

Dict = { 1 : {'name': 'Jack', 'age': 28}, 2 : {'name': 'John', 'age': 27} }


print(Dict[1][‘name’]) # output: Jack
print(Dict[2][‘age’]) # output: 27
Changing and Adding Dictionary elements

• Dictionaries are mutable. We can add new items or change the value of existing items
using an assignment operator.
• If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
Changing and Adding Dictionary elements

# Creating an empty Dictionary


Dict = { }
print(Dict) #output: { }

# Adding elements one at a time


Dict[‘name’] = ‘jack’
Dict[‘age’] = 28
Dict[3] = 100
print(Dict) #output: {‘name’: ‘jack', ‘age’: 28, 3: 100 }

# Adding set of values to a single Key


Dict['Values'] = 2, 3, 4
print(Dict) #output: {‘name’: ‘jack', ‘age’: 28, 3: 100, ‘Values’:(2, 3, 4) }
Changing and Adding Dictionary elements

# Changing and adding Dictionary Elements


my_dict = {'name': 'Jack', 'age': 29}

# update value
my_dict['age'] = 27
print(my_dict) #output : {'name': 'Jack', 'age': 27}

# add item
my_dict[‘city'] = ‘Mumbai’
print(my_dict) #output : {'name': 'Jack', 'age': 27, 'city': 'Mumbai'}

# Adding Nested Dictionary


my_dict['marks'] = {'phy':78, 'chem':90}
print(my_dict) #output: {'name': 'Jack', 'age': 27, 'city': 'Mumbai',
'marks': {'phy': 78, 'chem': 90}}
Removing elements from Dictionary

• We can remove a particular item in a dictionary by using the pop() method. This
method removes an item with the provided key and returns the value.

# Removing elements from a dictionary


squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value


print(squares.pop(4)) # Output: 16
print(squares) # Output: {1: 1, 2: 4, 3: 9, 5: 25}

my_dict ={'name': 'Jack', 'age': 27, 'city': 'Mumbai'}


pop_ele = my_dict.pop(‘age’)
print(pop_ele) #Output : 27
print(my_dict) #Output : {'name': 'Jack', 'city': 'Mumbai‘}
Removing elements from Dictionary

• The popitem() method can be used to remove and return an arbitrary (key, value) item
pair from the dictionary.

# Removing elements from a dictionary


squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value


print(squares.popitem( )) # Output: (5, 25)
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16}

my_dict ={'name': 'Jack', 'age': 27, 'city': 'Mumbai'}


pop_ele = my_dict.popitem( )
print(pop_ele) #Output : ('city', 'Mumbai')
print(my_dict) #Output : {'name': 'Jack', 'age': 27}
Removing elements from Dictionary

• All the items can be removed at once, using the clear() method.

# Removing elements from a dictionary


squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove all elements at once


squares.clear ( )
print(squares) # Output: { }

my_dict ={'name': 'Jack', 'age': 27, 'city': 'Mumbai'}


my_dict.clear( )
print(my_dict) #Output : { }
Removing elements from Dictionary

• We can also use the del keyword to remove individual items or the entire dictionary itself.

# Removing elements from a dictionary


squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# delete the dictionary itself


del square
print(squares) # Output: NameError: name 'squares' is not defined

my_dict ={'name': 'Jack', 'age': 27, 'city': 'Mumbai'}


del my_dict[‘age’]
print(my_dict) #Output : {'name': 'Jack', 'city': 'Mumbai'}

stud = {'name': 'Jack', 'age': 27, 'city': 'Mumbai', 'marks': {'phy': 78, 'chem': 90}}
del stud[‘marks’][‘phy’]
print(stud) # output : {'name': 'Jack', 'age': 27, 'city': 'Mumbai', 'marks': {'chem': 90}}
Basic Dictionary Operations

Python Expression Results Description

len({1:10 , 2:20, 3:30}) 3 Length


3 in {1:10, 2:20, 3:30} True Membership
1
for x in {1:10, 2:20, 3:30}:
2 Iteration
print(x)
3
Dictinoary Methods

Method Description
clear() Removes all items from the dictionary.

copy() Returns a shallow copy of the dictionary.

Returns a new dictionary with keys from seq and value equal to v (defaults
fromkeys(seq[, v])
to None).

Returns the value of the key. If the key does not exist, returns d (defaults to
get(key[,d])
None).

items() Return a new object of the dictionary's items in (key, value) format.

keys() Returns a new object of the dictionary's keys.


Dictionary Methods

Method Description

Removes the item with the key and returns its value or d if key is not found.
pop(key[,d])
If d is not provided and the key is not found, it raises KeyError.

Removes and returns an arbitrary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.

Returns the corresponding value if the key is in the dictionary. If not,


setdefault(key[,d])
inserts the key with a value of d and returns d (defaults to None).

Updates the dictionary with the key/value pairs from other, overwriting
update([other])
existing keys.

values() Returns a new object of the dictionary's values


Dictionary Functions

Method Description

Return True if all keys of the dictionary are True (or if the dictionary is
all()
empty).

Return True if any key of the dictionary is true. If the dictionary is empty,
any()
return False.

len() Return the length (the number of items) in the dictionary.

cmp() Compares items of two dictionaries. (Not available in Python 3)

sorted() Return a new sorted list of keys in the dictionary.

You might also like