[go: up one dir, main page]

0% found this document useful (0 votes)
27 views29 pages

Unit 4

Uploaded by

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

Unit 4

Uploaded by

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

UNIT IV

Dictionaries are used to store data values in key: value pairs. A dictionary is a
collection which is ordered, changeable and do not allow duplicates.

Python dictionary is an ordered collection of items. It stores elements in key/value


pairs. Here, keys are unique identifiers that are associated with each value.

Here, keys are unique identifiers that are associated with each value.

Creating a Dictionary:

 A dictionary can be created by placing a sequence of elements within curly {}


braces, separated by ‘comma’.
 Dictionary holds pairs of values, one being the Key and the other corresponding
pair element being its Key:value.
 Values in a dictionary can be of any data type and can be duplicated, whereas
keys can’t be repeated and must be immutable.
 Dictionary keys are case sensitive, the same name but different cases of Key
will be treated distinctly.

EXAMPLE:

capital_city = {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}

print(capital_city)

OUTPUT:

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

In the above example, a dictionary is created with named capital_city.

Here,

 Keys are "Nepal", "Italy", "England"


 Values are "Kathmandu", "Rome", "London"

Dictionary can also be created by the built-in function dict(). An empty dictionary can
be created by just placing to curly braces {}.

EXAMPLE:
Dict = {}

print("Empty Dictionary: ")


print(Dict)

Output: {}

Adding elements to a Dictionary

Addition of elements can be done in multiple ways. One value at a time can be added
to a Dictionary by defining value along with the key

e.g. Dict[Key] = ‘Value’.

Accessing elements of a Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets.

EXAMPLE:

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key

print("Accessing a element using key:")

print(Dict['name'])

# accessing a element using key

print("Accessing a element using key:")

print(Dict[1])

Output:

Accessing a element using key:


For
Accessing a element using key:
Geeks

Dictionary methods
 clear() – Remove all the elements from the dictionary
 copy() – Returns a copy of the dictionary
 get() – Returns the value of specified key
 items() – Returns a list containing a tuple for each key value pair
 keys() – Returns a list containing dictionary’s keys
 pop() – Remove the element with specified key
 popitem() – Removes the last inserted key-value pair
 update() – Updates dictionary with specified key-value pairs
 values() – Returns a list of all the values of dictionary

EXAMPLE:
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}

# copy() method
dict2 = dict1.copy()
print(dict2)
# clear() method
dict1.clear()
print(dict1)
# get() method
print(dict2.get(1))
# items() method
print(dict2.items())
# keys() method
print(dict2.keys())
# pop() method
dict2.pop(4)
print(dict2)

# popitem() method
dict2.popitem()
print(dict2)
# update() method
dict2.update({3: "Scala"})
print(dict2)
# values() method
print(dict2.values())
output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Dictionary operations

1. Definition operations
These operations allow us to define or create a dictionary.
1.1.{ }
Creates an empty dictionary or a dictionary with some initial values.
y = {}
x = {1: "one", 2: "two", 3: "three"}

2. Mutable operations
These operations allow us to work with dictionaries, but altering or modifying their
previous definition.
2.1. [ ]
Adds a new pair of key and value to the dictionary, but in case that the key already
exists in the dictionary, we can update the value.
y = {}
y['one'] = 1
y['two'] = 2
print(y)
Output:
{'one': 1, 'two': 2}
y['two'] = 'dos'
print(y)
Output:
{'one': 1, 'two': 'dos'}
2.2. del
Del statement can be used to remove an entry (key-value pair) from a dictionary.

y = {'one': 1, 'two': 2}
print(y)
Output:
{'one': 1, 'two': 2}
del y['two']
print(y)
Output:
{'one': 1}
2.3. Update
This method updates a first dictionary with all the key-value pairs of a second
dictionary. Keys that are common to both dictionaries, the values from the second
dictionary override those of the first.

x = {'one': 0, 'two': 2}
y = {'one': 1, 'three': 3}
x.update(y)
print(x)
Output:
{'one': 1, 'two': 2, 'three': 3}

3. Immutable operations

These operations allow to work with dictionaries without altering or modifying their
previous definition.
3.1. len
Returns the number of entries (key-value pairs) in a dictionary.
x = {'one': 0, 'two': 2}
print(len(x))
Output:2
3.2. Keys
This method allows you to get all the keys in the dictionary. It is often used in a “for
loop” to iterate over the content of a dictionary.
x = {'one': 1, 'two': 2}
print(x.keys())
Output:dict_keys(['one', 'two'])
3.3. Values
This method allows you to obtain all the values stored in a dictionary.
x = {'one': 1, 'two': 2}
print(x.values())
Output:dict_values([1, 2])

3.4. Items
Returns all the keys and their associated values as a sequence of tuples.
x = {'one': 1, 'two': 2}
print(x.items())
Output:dict_items([('one', 1), ('two', 2)])

3.5. in
Attempting to access a key that is not in a dictionary will raise an exception. To
handle this exception, the in method is used to test whether a key exists in a
dictionary, returns True if a dictionary has a value stored under the given key and
False otherwise.
y = {'one': 1, 'two': 2}
del y['three']
Output: KeyError: 'three'y = {'one': 1, 'two': 2}if 'three' in y:
del y['three']

print(y)Output:{'one': 1, 'two': 2}
3.6. Get
Returns the value associated with a key if the dictionary contains that key, in case that
the dictionary does not contain the key, you can specified a second optional argument
to return a default value, if the argument is not included get method will return None.
y = {'one': 1, 'two': 2}
print(y.get('one'))
print(y.get('three'))
print(y.get('three', 'The key does not exist.'))
Output:
1
None
The key does not exist.

LISTS

 A list in Python is used to store the sequence of various types of data. A list can
be defined as a collection of values or items of different types.

 Python lists are mutable type which implies that we may modify its element
after it has been formed.

 The items in the list are separated with the comma (,) and enclosed with the
square brackets [].

Characteristics of Lists

The list has the following characteristics:

o The lists are ordered.


o The element of the list can access by index.
o The lists are the mutable type.
o A list can store the number of various elements.

Example:

A list can have any number of items and they may be of different types (integer, float,
string, etc.). For example,

# empty list
my_list = []

# list with mixed data types

my_list = [1, "Hello", 3.4]

Access Python List Elements

 In Python, each item in a list is associated with a number. The number is known
as a list index. The elements of the list can be accessed by using the slice
operator [].
 The index starts from 0 and goes to length - 1. 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.

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

 The sub-list of the list can be get using the following syntax.

list_varible[start:stop:step]

o The start denotes the starting index position of the list.


o The stop denotes the last index position of the list.
o The step is used to skip the nth element within a start:stop
o In the absence of a specific value for step, the default value equals 1

Example:

list = [1,2,3,4,5,6,7]
print(list[0])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
print(list[:])
print(list[2:5])
print(list[-1])
OUTPUT:
1
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
7

Python List Methods


Python has many useful list methods that makes it really easy to work with lists.

Method Description

append() add an item to the end of the list


extend() add items of lists and other iterables to the end of the list

insert() inserts an item at the specified index

remove() removes item present at the given index

pop() returns and removes item present 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 specified item in the list

sort() sort the list in ascending/descending order

reverse() reverses the item of the list

copy() returns the shallow copy of the list

Code
l =[]
n = int(input("Enter the number of elements in the list:"))
for i in range(0,n):
l.append(input("Enter the item:"))
print("printing the list items..")
for i in l:
print(i, end = " ")
l.remove(1)
for i in l:
print(i, end = " ")
Output:
Enter the number of elements in the list:3
Enter the item:32
Enter the item:56
Enter the item:81
printing the list items..
32 56 81
printing the list items..
32 81
Python List Operations
. The different operations of list are
 Repetition
 Concatenation
 Length
 Iteration
 Membership
1. Repetition
The repetition operator enables the list elements to be repeated multiple times.
Code
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length
It is used to get the length of the list
Code:
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
len(list1)
Output:
9
4. Iteration
The for loop is used to iterate over the list elements.
Code
list1 = [12, 14, 16, 39, 40]
for i in list1:
print(i)
Output:
12
14
16
39
40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
list1 = [100, 200, 300, 400, 500]
print(600 in list1)
print(300 in list1)
print(100 in list1)
Output:
False
True
True

Python List Built-in Functions


Python provides the following built-in functions, which can be used with the lists.
 len()
 max()
 min()
1. len( )
It is used to calculate the length of the list.
Code
list1 = [12, 16, 18, 20, 39, 40]
len(list1)
Output:
6
2. Max( )
It returns the maximum element of the list
Code
list1 = [103, 675, 321, 782, 200]
print (max(list1))
Output:
782
3. Min( )
It returns the minimum element of the list
Code
list1 = [103, 675, 321, 782, 200]
print (min(list1))
Output:
103

TUPLE DATA TYPE

A tuple represents a sequence of any objects separated by commas and enclosed in


parentheses.

A tuple is an immutable object, which means it cannot be changed, and it is used to


represent fixed collections of items.

or

A tuple is a collection of objects which ordered and immutable. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square
brackets.

1Creating a Tuple

A tuple is created by placing all the items (elements) inside parentheses (), separated
by commas.

A tuple can have any number of items and they may be of different types (integer,
float, list, string, etc.).
Example:

# Different types of tuples

# Empty tuple

my_tuple = ()

print(my_tuple)

# Tuple having integers

my_tuple = (1, 2, 3)

print(my_tuple)

# tuple with mixed datatypes

my_tuple = (1, "Hello", 3.4)

print(my_tuple)

# nested tuple

my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

print(my_tuple)

Output

()

(1, 2, 3)

(1, 'Hello', 3.4)

('mouse', [8, 4, 6], (1, 2, 3))

Access Python Tuple Elements

Each element of a tuple is represented by index numbers (0, 1, ...) where the first
element is at index 0.

The index number is used to access tuple elements. For example,


1. Indexing

The index operator [] is used to access an item in a tuple, where the index starts from
0.

# accessing tuple elements using indexing

Example:

letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")

print(letters[0])

print(letters[5])

Output:

prints "p"

prints "a"

2.Slicing

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

For example:

# accessing tuple elements using slicing

my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

print(my_tuple[1:4])

print(my_tuple[7:])

print(my_tuple[:])

output:

prints ('r', 'o', 'g')

prints ('i', 'z')

Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.

In fact, tuples respond to all of the general sequence operations used on strings .

Python Expression Results Description

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

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

There are a few methods that can be used on tuples.

The most common is the index() method, which can be used to find the position of a
given element in the tuple:

The method count (), which returns the number of times a given element appears in
the tuple:

Example:

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


print(my_tuple.count('p'))

print(my_tuple.index('l'))

output:

Built-in Tuple Functions

Python includes the following tuple functions −

S.No. Function with Description

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

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

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

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

tuple(seq)
5 Converts a list into tuple.

Python Set
A Python set is the collection of the unordered items. Each element in the set
must be unique, immutable, and the sets remove the duplicate elements. Sets are
mutable which means we can modify it after its creation.
(Or)
Sets are used to store multiple items in a single variable. A set is a collection
which is unordered, unchangeable (but the items can be removed and add new items)
and unindexed. Sets are written with curly brackets {}.
Example
thisset = {"apple", "banana", "cherry"}
print(thisset)
print(type(thisset))
Output: {'banana', 'apple', 'cherry'}
<class 'set'>
Methods in SET:
 Python provides the add() method and update() method which can be used to
add some particular item to the set.
 The add() method is used to add a single element whereas the update() method
is used to add multiple elements to the set.
 The discard() method and remove() method is used to remove the specified
element from a set.
 The difference between these function, using discard() function if the item does
not exist in the set then the set remain unchanged whereas remove() method
will through an error.
 The del keyword will delete the set completely.
 The pop() method is used to remove a random item.

Example:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
thisset.remove("banana")
print(thisset)
thisset.clear()
print(thisset)

Output:
{'orange', 'cherry', 'apple', 'banana'}
{'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}
{'apple', 'mango', 'cherry', 'pineapple', 'papaya'}
set()

Built-in Functions with Set


Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum()
etc. are commonly used with sets to perform different tasks.

 Function  Description

 Returns True if all elements of the set are true (or


 all()
if the set is empty).

 Returns True if any element of the set is true. If


 any()
the set is empty, returns False.

 Returns an enumerate object. It contains the


 enumerate() index and value for all the items of the set as a
pair.
 Returns the length (the number of items) in the
 len()
set.

 max()  Returns the largest item in the set.

 min()  Returns the smallest item in the set.

 Returns a new sorted list from elements in the


 sorted()
set(does not sort the set itself).

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

Python Set Operations

Python Set provides different built-in methods to perform mathematical set operations
like union, intersection, subtraction, and symmetric difference.

Union of Two Sets

The union of two sets A and B include all the elements of set A and B. The | operator
or the union() method is used to perform the set union operation. For example,

# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
# perform union operation using |
print('Union using |:', A | B)
# perform union operation using union()
print('Union using union():', A.union(B))

Output
Union using |: {0, 1, 2, 3, 4, 5}
Union using union(): {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.The & operator or the intersection() method is used to perform the set intersection
operation.
Difference between Two Sets
The difference between two sets A and B include elements of set A that are not
present on set B. The - operator or the difference() method is used to perform the
difference between two sets.
Set Symmetric Difference
The symmetric difference between two sets A and B includes all elements of A and B
without the common elements. The ^ operator or the symmetric_difference() method
is used to perform symmetric difference between two sets.
Example:
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# perform difference operation using &
print('using ^:', A ^ B)
Output:
using ^: {1, 3, 5, 6}

Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance
provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class.
In 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.
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the
bracket.
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
The issubclass(sub,sup) method
The issubclass(sub, sup) method is used to check the relationships between the
specified classes. It returns true if the first class is the subclass of the second class, and
false otherwise.
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(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Output:

True
False
The isinstance (obj, class) method
The isinstance() method is used to check the relationship between the objects
and classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.

Encapsulation:
Encapsulation is one of the most fundamental concepts in object-oriented
programming (OOP). This is the concept of wrapping data and methods that work
with data in one unit. This prevents data modification accidentally by limiting access
to variables and methods. Encapsulation is demonstrated by a class which
encapsulates all data, such as member functions, variables, and so forth.
EXAMPLE:
class Employee:
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project
# method
def show(self):
print("Name: ", self.name, 'Salary:', self.salary)
# method
def work(self):
print(self.name, 'is working on', self.project)
# creating object of a class
emp = Employee('Jessa', 8000, 'NLP')
# calling public method of the class
emp.show()
emp.work()
Output:
Name: Jessa Salary: 8000
Jessa is working on NLP
Encapsulation allows us to restrict accessing variables and methods directly and
prevent accidental data modification by creating private data members and methods
within a class. Encapsulation is a way to can restrict access to methods and variables
from outside of class.
Encapsulation can be achieved by declaring the data members and methods of a
class either as private or protected.
Access modifiers limit access to the variables and methods of a class. Python
provides three types of access modifiers private, public, and protected. But in Python,
we don’t have direct access modifiers like public, private, and protected. It can
achieved this by using single underscore and double underscores.

 Public Member: Accessible anywhere from outside oclass.


 Private Member: Accessible within the class
 Protected Member: Accessible within the class and its sub-classes

Example:

class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary

# creating object of a class


emp = Employee('Jessa', 10000)

# accessing private data members


print('Salary:', emp.__salary)
Output
AttributeError: 'Employee' object has no attribute '__salary'

Polymorphism

Polymorphism is another important concept of object-oriented programming. It


simply means more than one form.

That is, the same entity (method or operator or object) can perform different
operations in different scenarios

Example:

class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")

class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")

class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")

# create an object of Square


s1 = Square()
s1.render()

# create an object of Circle


c1 = Circle()
c1.render()
Output
Rendering Square...
Rendering Circle...
In the above example, we have created a superclass: Polygon and two
subclasses: Square and Circle. Notice the use of the render() method.
The main purpose of the render() method is to render the shape. However, the
process of rendering a square is different from the process of rendering a circle.
Hence, the render() method behaves differently in different classes.

You might also like