Unit 5
Unit 5
Dictionaries are Python’s implementation of a data structure that is more generally known as an
associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair
maps the key to its associated value.
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly
braces ({}). A colon (:) separates each key from its associated value:
d={
<key>: <value>,
<key>: <value>,
<key>: <value>
You can also construct a dictionary with the built-in dict() function. The argument to dict()
should be a sequence of key-value pairs. A list of tuples works well for this:
d = dict([
(<key>, <value>),
(<key>, <value),
(<key>, <value>)
])
Access Dictionary Items
We can access the value of a dictionary item by placing the key inside square brackets.
country_capitals = {
"Italy": "Rome",
"England": "London"
print(country_capitals["England"]) # London
Python dictionaries are mutable (changeable). We can change the value of a dictionary element
by referring to its key. For example,
country_capitals = {
"Italy": "Naples",
"England": "London"
country_capitals["Italy"] = "Rome"
print(country_capitals)
Output
country_capitals = {
"Italy": "Naples"
country_capitals["Germany"] = "Berlin"
print(country_capitals)
Output
Note: We can also use the update method() to add or change dictionary items.
We use the del statement to remove an element from the dictionary. For example,
country_capitals = {
"Italy": "Naples"
print(country_capitals)
If we need to remove all items from the dictionary at once, we can use the clear() method.
country_capitals = {
"Italy": "Naples"
country_capitals.clear()
print(country_capitals) # {}
Function Description
Note: The in operator checks whether a key exists; it doesn't check whether a value exists or not.
Iterating Through a Dictionary
A dictionary is an ordered collection of items (starting from Python 3.7). Meaning a dictionary
maintains the order of its items.
We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"Italy": "Naples"
print(country)
print("----------")
capital = country_capitals[country]
print(capital)
set
A set is a collection of unique data. That is, elements of a set cannot be duplicate. For example,
Suppose we want to store information about student IDs. Since student IDs cannot be duplicate,
we can use a set.
In Python, we create sets by placing all the elements inside curly braces {}, separated by comma.
A set 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.
Let's see an example,
Immutable set
Python Method creates an immutable Set object from an iterable. It is a built-in Python function.
As it is a set object, therefore, we cannot have duplicate values in the frozenset.
print("cat" in animals)
print("elephant" in animals)
Syntax : frozenset(iterable_object_name)
Let's see what will happen if we try to include duplicate items in a set.
numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # {8, 2, 4, 6}
Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.
We cannot access or change an element of a set using indexing or slicing. Set data type does not
support it.
In Python, we use the add() method to add an item to a set. For example,
print('Initial Set:',numbers)
numbers.add(32)
Output
In the above example, we have created a set named numbers. Notice the line,
numbers.add(32)
The update() method is used to update the set with items other collection types (lists, tuples, sets,
etc). For example,
companies.update(tech_companies)
print(companies)
We use the discard() method to remove the specified element from a set. For example,
print('Initial Set:',languages)
removedValue = languages.discard('Java')
Output
Here, we have used the discard() method to remove 'Java' from the languages set.
print(fruit)
Output
Mango
Peach
Apple
We can use the len() method to find the number of elements present in a Set. For example,
even_numbers = {2,4,6,8}
print('Set:',even_numbers)
Output
Set: {8, 2, 4, 6}
Total Elements: 4
Here, we have used the len() method to find the number of elements present in a Set.
Python Set provides different built-in methods to perform mathematical set operations like
union, intersection, difference, and symmetric difference.
The union of two sets A and B include all the elements of set A and B.
We use the | operator or the union() method to perform the set union operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
Output
Union using |: {0, 1, 2, 3, 4, 5}
Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
In Python, we use the & operator or the intersection() method to perform the set intersection
operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
Output
The difference between two sets A and B include elements of set A that are not present on set B.
We use the - operator or the difference() method to perform the difference between two sets. For
example,
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
Output
The symmetric difference between two sets A and B includes all elements of A and B without the
common elements.
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
print('using ^:', A ^ B)
# using symmetric_difference()
using ^: {1, 3, 5, 6}
We can use the == operator to check whether two sets are equal or not. For example,
# first set
A = {1, 3, 5}
# second set
B = {3, 5, 1}
if A == B:
else:
Output
In the above example, A and B have the same elements, so the condition
if A == B
evaluates to True. Hence, the statement print('Set A and Set B are equal') inside the if is executed.
There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with the set objects:
Method Description
discard() Removes an element from the set if it is a member. (Do nothing if the
element is not in set)
pop() Removes and returns an arbitrary set element. Raises KeyError if the set is
empty
remove() Removes an element from the set. If the element is not a member, raises
a KeyError
update() Updates the set with the union of itself and others
In Python, almost everything is an object, with its properties and methods. A Class is like an
object blueprint, from which objects can be created. Objects can inherit properties and methods
from other objects, and they can also be extended to add new properties and methods.
Classes: Classes are blueprints for creating objects. They define the properties and methods that
objects will have.
Objects: Objects are instances of classes. They have the properties and methods defined by their
class.
Example:
class Person:
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
he __init__() Function
The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated.
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
The __str__() function controls what should be returned when the class object is represented as a
string.
If the __str__() function is not set, the string representation of the object is returned:
Example
class Person:
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Inheritance
Inheritance is a feature of object-oriented programming that allows you to create a new class that
inherits from an existing class. The new class, called the subclass, inherits all of the properties
and methods of the existing class, called the base class.
Inheritance in Python is implemented using the class keyword. To create a subclass, you simply
specify the base class in the parentheses after the class name.
For example, the following code creates a subclass called Dog that inherits from the Animal
class:
class Animal:
def eat(self):
print("I'm eating!")
class Dog(Animal):
def bark(self):
print("Woof!")
The Dog class inherits all of the methods of the Animal class, including eat(). It also has its own
method, bark().
python, a derived class can inherit base class by just mentioning the base in the bracket after the
derived class name. Consider the following syntax to inherit a base class into the derived class.
python, a derived class can inherit base class by just mentioning the base in the bracket after the
derived class name. Consider the following syntax to inherit a base class into the derived class.
Python Inheritance
Syntax
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Python provides us the flexibility to inherit multiple base classes in the child class.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
class BaseN:
<class-suite>
<class-suite>
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
Encapsulation
Encapsulation is one of the critical features of object-oriented programming, which involves the
bundling of data members and functions inside a single class. Bundling similar data members
and functions inside a class also helps in data hiding. Encapsulation also ensures that objects are
self-sufficient functioning pieces and can work independently.
The primary advantage of using Encapsulation in Python is that as a user, we do not need to
know the architecture of the methods and the data and can just focus on making use of these
functional, encapsulated units for our applications. This results in a more organized and clean
code. The user experience also improves greatly and makes it easier to understand applications as
a whole.
Another advantage of encapsulation is that it prevents the accidental modification of the data and
methods. Let’s consider the example of NumPy again, if I had access to edit the library, then I
might make a mistake in the implementation of the mean function and then because of that
mistake, thousands of projects using NumPy would become inaccurate.
Encapsulation in Python is achieved through the access modifiers. These access modifiers ensure
that access conditions are not breached and thus provide a great user experience in terms of
security.
It is easier to reuse code when it is encapsulated. Creating objects that contain common
functionality allows us to reuse them in many settings.
Sometimes there might be a need to restrict or limit access to certain variables or functions while
programming. That is where access modifiers come into the picture.
Now when we are talking about access, 3 kinds of access specifiers can be used while
performing Encapsulation in Python. They are as follows :
Public Members
Private Members
Protected Members
As the name suggests, the public modifier allows variables and functions to be accessible from
anywhere within the class and from any part of the program. All member variables have the
access modifier as public by default.
Now let’s check out how we can implement Encapsulation in Python using public methods –
class pub_mod:
# constructor
self.name = name;
self.age = age;
def Age(self):
# creating object
Evidently, from the above code, you can make out that we declared two variables and two
methods of the class pub_mod. We were able to access the variables and methods wherever we
wanted with ease as the access modifier for them was public, which means they should be
accessible everywhere.
Name: Jason
Age: 35
The private access modifier allows member methods and variables to be accessed only within the
class. To specify a private access modifier for a member, we make use of the double underscore
__.
Let’s check out this example to understand how we can implement Encapsulation using private
members –
class Rectangle:
def __init__(self):
#constructor
self.__length = 5
self.__breadth = 3
print(self.__length)
print(self.__breadth)
rect = Rectangle() #object created
print(rect.length)
print(rect.breadth)
We have accessed len both within and outside the class in the above snippet. Let’s see what kind
of output that gives us.
Output –
What sets protected members apart from private members is that they allow the members to be
accessed within the class and allow them to be accessed by the sub-classes involved. In Python,
we demonstrate a protected member by prefixing with an underscore _ before its name.
As we know, if the members have a protected access specifier, it can also be referenced then
within the class and the subsequent sub-clas
class details:
_name="Jason"
_age=35
_job="Developer"
class pro_mod(details):
def __init__(self):
print(self._name)
print(self._age)
print(self._job)
obj = pro_mod()
print("Name:",obj.name)
print("Age:",obj.age)
Output –
Jason
35
Developer
It is quite clear from the output that the class pro_mod was successfully able to inherit the
variables from the class details and print them to the console, although they were protected
variables. And when we tried to refer to them outside of their parent class and the sub-class, we
got an AttributeError for the same.
Polymorphism
Polymorphism means multiple forms. In python we can find the same operator or function taking
multiple forms. It also useful in creating different classes which will have class methods with
same name. That helps in re using a lot of code and decreases code complexity. Polymorphism is
also linked to inheritance as we will see in some examples below.
Polymorphism in operators
The + operator can take two inputs and give us the result depending on what the inputs are. In the
below examples we can see how the integer inputs yield an integer and if one of the input is float
then the result becomes a float. Also for strings, they simply get concatenated. This happens
automatically because of the way the + operator is created in python.
Example
a = 23
b = 11
c = 9.5
s1 = "Hello"
s2 = "There!"
print(a + b)
print(type(a + b))
print(b + c)
print(type (b + c))
print(s1 + s2)
print(type(s1 + s2))
Output
34
20.5
HelloThere!
We can also see that different python functions can take inputs of different types and then
process them differently. When we supply a string value to len() it counts every letter in it. But if
we five tuple or a dictionary as an input, it processes them differently.
Example
tup = ('Mon','Tue','wed','Thu','Fri')
lst = ['Jan','Feb','Mar','Apr']
dict = {'1D':'Line','2D':'Triangle','3D':'Sphere'}
print(len(str))
print(len(tup))
print(len(lst))
print(len(dict))
Output
10
We can create methods with same name but wrapped under different class names. So we can
keep calling the same method with different class name pre-fixed to get different result. In the
below example we have two classes, rectangle and circle to get their perimeter and area using
same methods.
Example
class Rectangle:
self.l = length
self.b = breadth
def perimeter(self):
class Circle:
self.r = radius
def perimeter(self):
return 2 * pi * self.r
def area(self):
return pi * self.r ** 2
rec = Rectangle(5,3)
cr = Circle(4)
Output
Perimter of rectangel: 16
Area of rectangel: 15