0% found this document useful (0 votes)
86 views74 pages

BPP Unit 4

The document discusses data structures in Python. It describes that data structures allow organizing and storing data in a way that enables easy access and modifications. The main data structures in Python are lists, dictionaries, tuples, and sets. Lists are ordered collections that allow storing heterogeneous data and accessing elements by index. Elements can be added, removed, or updated in lists using various methods. Lists also support operations like slicing, nesting, and cloning.

Uploaded by

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

BPP Unit 4

The document discusses data structures in Python. It describes that data structures allow organizing and storing data in a way that enables easy access and modifications. The main data structures in Python are lists, dictionaries, tuples, and sets. Lists are ordered collections that allow storing heterogeneous data and accessing elements by index. Elements can be added, removed, or updated in lists using various methods. Lists also support operations like slicing, nesting, and cloning.

Uploaded by

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

UNIT 4

DATA STRUCTURES

What is a Data Structure?

Organizing, managing and storing data is important as it enables easier access and
efficient modifications. Data Structures allows you to organize your data in such a way that
enables you to store collections of data, relate them and perform operations on them
accordingly.

Types of Data Structures in Python

Python has implicit support for Data Structures which enable you to store and access
data. These structures are called List, Dictionary, Tuple and Set. these Data Structures are
built-in with Python which makes programming easier and helps programmers use them to
obtain solutions faster.

Sequence

Sequences allow you to store multiple values in an organized and efficient fashion.
The different Python data structures can be divided into two categories based on the ordering
of items: Sequences and Collections. Elements in sequences come out in the same order as
it is inserted, however ordering in collections is not preserved.

In Python programming, sequences are a generic term for an ordered set which
means that the order in which we input the items will be the same when we access them.
Python supports six different types of sequences. These are strings, lists, tuples, byte
sequences, byte arrays, and range objects.

A sequence is a positionally ordered collection of items. And you can refer to any
item in the sequence by using its index number e.g., s[0] and s[1]. In Python, the sequence
index starts at 0, not 1. So the first element is s[0] and the second element is s[1]. If the
sequence s has n items, the last item is s[n-1].

The mutable sequence types are lists and bytearrays while the immutable sequence
types are strings, tuples, range, and bytes. A sequence can be homogeneous or heterogeneous.
In a homogeneous sequence, all elements have the same type. For example, strings are
homogeneous sequences where each element is of the same type. Lists, however, are
heterogeneous sequences where you can store elements of different types including integer,
strings, objects, etc. In general, homogeneous sequence types are more efficient than
heterogeneous in terms of storage and operations.

Lists

In Python, lists are ordered collections of items that allow for easy use of a set of data.
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of
elements. Each element or value that is inside of a list is called an item. List values are placed
in between square brackets [ ], separated by commas. It is good practice to put a space
between the comma and the next value. The values in a list do not need to be unique (the
same value can be repeated). Empty lists do not contain any values within the square
brackets.

Create Python Lists

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


print(my_list) print(mylist)
O/P: [1, 2, 3] O/P: []

names=["Jeff", "Bill", "Steve", "Mohan"] # item=[1, "Jeff", "Computer", 75.50, True] #


string list list with heterogeneous data
print(names) print(item)
O/P: ["Jeff", "Bill", "Steve", "Mohan"] O/P: [1, "Jeff", "Computer", 75.50, True]

Accessing elements from the List

In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list. The index must be an integer. Each item in a list has an assigned index
value. It is important to note that python is a zero indexed based language. All this means is
that the first item in the list is at index 0.

my_list = ['p', 'r', 'o', 'b', 'e']

print(my_list[0]) # first item

print(my_list[2]) # third item

print(my_list[4]) # fifth item

Output
p

The format for list slicing is [start:stop:step].

• start is the index of the list where slicing starts.

• stop is the index of the list where slicing ends.

• step allows you to select nth item within the range start to stop.

Program to demonstrate the slice operations used to access the elements of the list

my_list = [1, 2, 3, 4, 5]

print(my_list[:])

print(my_list[2:])

print(my_list[:2])

print(my_list[2:4])

print(my_list[::2])

print(my_list[::-2])

print(my_list[1:4:2])

Output

[1, 2, 3, 4, 5]

[3, 4, 5]

[1, 2]

[3, 4]

[1, 3, 5]

[5, 3, 1]

[2, 4]
update values in a List

In Python, lists are mutable. It means we can change the list’s contents by adding, updating,
or removing elements from the list. In Python, we can use list methods append(), insert(), and
extend() to add the elements to the list. we can use list methods clear(), pop(), and remove()
to remove the elements from the list.

Insert item using append() method

# Define the list


listdata = ["Dell", "HP", "Leveno", "Asus"]
# Insert data using append method
listdata.append("Toshiba")
# Display the list after insert
print("The list elements are")
for i in range(0, len(listdata)):
print(listdata[i])

Output:

The list elements are

Dell

HP

Leveno

Asus

Toshiba

Insert item using insert() method

# Declare list
listdata = [89, 56, 90, 34, 89, 12]
# Insert data in the 2nd position
listdata.insert(2, 23)
# Displaying list after inserting
print("The list elements are")
for i in range(0, len(listdata)):
print(listdata[i])

Output:

The list elements are

89

56

23

90

34

89

12

Insert item using extend() method

# initializing the first list


list1 = ['html', 'CSS', 'JavaScript', 'JQuery']
# initializing the second list
list2 = ['PHP', 'Laravel', 'CodeIgniter']
# Combine both lists using extend() method
list1.extend(list2)
# Display the list after combing
print ("The list elements are :")
for i in range(0, len(list1)):
print(list1[i])

Output:

The list elements are :

html

CSS

JavaScript
JQuery

PHP

Laravel

CodeIgniter

Remove item from the list using the remove method

# Define the list


list = ['Cake', 'Pizza', 'Juice', 'Pasta', 'Burger']
# Print the list before delete
print("List before delete")
print(list)
# Remove an item
list.remove('Juice')
# Print the list after delete
print("List after delete")
print(list)

Output:

List before delete

['Cake', 'Pizza', 'Juice', 'Pasta', 'Burger']

List after delete

['Cake', 'Pizza', 'Pasta', 'Burger']

Remove item from the list using pop method

# Define the list


ldata = [ 34, 23, 90, 21, 90, 56, 87, 55]
# Print the before remove
print(ldata)
# Remove the third element
ldata.pop(2)
# Print the list after remove
print(ldata)
Output:

[34, 23, 90, 21, 90, 56, 87, 55]

[34, 23, 21, 90, 56, 87, 55]

Remove item from the list using del method and clear() method

# Define the list


ldata = [ 34, 23, 90, 21, 90, 56, 87, 55]
# Print the before remove
print(ldata)
# Delete the first item using del method
del ldata[0]
# Print the list after remove
print(ldata)

# Remove all items from the list


ldata.clear()
# Print the list after clear
print(ldata)

Output:

[34, 23, 90, 21, 90, 56, 87, 55]

[23, 90, 21, 90, 56, 87, 55]

[]

Nested lists:

A nested list is a list of lists, or any list that has another list as an element (a sublist). They
can be helpful if you want to create a matrix or need to store a sublist along with other data
types.

# creating list

nestedList = [1, 2, ['a', 1], 3]

# indexing list: the sublist has now been accessed

subList = nestedList[2]
# access the first element inside the inner list:

element = nestedList[2][0]

print("List inside the nested list: ", subList)

print("First element of the sublist: ", element)

Output:

List inside the nested list: ['a', 1]

First element of the sublist: a

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.

original_list = [1, 2, 3]

# create new copy using slicing

copy_list = original_list[:]

# modify first element of copy

copy_list[0] = 2

# print original list

print(original_list)

# print copied list

print(copy_list)

Output:

[1, 2, 3]

[2, 2, 3]

Basic list operations


Operation Description Example Output
len() It calculates the length of the list. >>> len(even) 4
max() It returns the item from the list print(max([1, 2, 3])) 3
with the highest value.
min() It returns the item from the Python print(min([1, 2, 3])) 1
list with the lowest value.
sum() It returns the sum of all the >>> sum([9,3,2,5,1,- 20
elements in the list. 9], 9)
any() It returns True if even one item in >>> any(['','','1']) True
the Python list has a True value.
all() It returns True if all items in the >>> all(['','','1']) True
list have a True value.
reversed() returns a reverse iterator in which >>> numbers = [23, -9, 21,
we can request the next value or [4,3,10,6,21,-9,23] 6, 10, 3, 4]
iterate through until we hit the end. >>>
list(reversed(numbers))
Concatenation It concatenates the list mentioned l1 = [1, 2, 3, 4] [1, 2, 3, 4,
on either side of the operator. l2 = [5, 6, 7, 8] 5, 6, 7, 8]
print(l1+l2)
Repetition The repetition operator enables the l1 = [1, 2, 3, 4] [1, 2, 3, 4,
list elements to be repeated print(l1*2) 1, 2, 3, 4]
multiple times.
sorted() returns a new sorted list of items >>> numbers = [23, 21, 10,
from an iterable. [4,3,10,6,21,9,23] 9, 6, 4, 3]
>>> sorted(numbers,
reverse=True)
List Methods

Method Description Example Output


append(x) Appends element x to the list >>> l = [] [42, 21]
>>> l.append(42)
>>> l.append(21)
clear() Removes all elements from the list >>> lst = [1, 2, 3, 4, 5] []
>>> lst.clear()
copy() Returns a copy of the list >>> lst = [1, 2, 3] [1, 2, 3]
>>> lst.copy()
count(x) Counts the number of occurences >>> lst = [1, 2, 42, 2, 3
of the element x 1, 42, 42]
>>> lst.count(42)
Extend() Adds the elements to the end of the >>> lst = [1, 2, 3] [1, 2, 3, 4,
list >>> lst.extend([4, 5, 5, 6]
6])
Index() Returns the position of the element >>> lst = ["Alice", 42, 0
"Bob", 99]
>>> lst.index("Alice")
Insert() Inserts the element at the specified >>> lst = [1, 2, 3, 4] [1, 2, 3, 99,
position >>> lst.insert(3, 99) 4]
pop() Removes and returns the last >>> lst = [1, 2, 3] 3
element of the list >>> lst.pop()
Remove() Removes the first occurrence of the >>> lst = [1, 2, 99, 4, [1,2,4,99]
element in the list 99]
>>> lst.remove(99)
reverse() Reverses the order of elements in >>> lst = [1, 2, 3, 4] [4,3,2,1]
the list >>> lst.reverse()
sort() Sort the elements in ascending >>> lst = [88, 12, 42, [2, 11, 12,
order 11, 2] 42, 88]
>>> lst.sort()
Using List as Stack

First of all, we must aware with the Stack - the stack is a linear data structure that works
on LIFO mechanism i.e. Last In First Out (that means Last inserted item will be removed
(popped) first).

Thus, to implement a stack, basically we have to do two things:

1. Inserting (PUSH) elements at the end of the list

2. Removing (POP) elements from the end of the list


i.e. both operations should be done from one end.

In Python, we can implement a stack by using list methods as they have the capability to
insert or remove/pop elements from the end of the list.

Method that will be used:

1. append(x) : Appends x at the end of the list

2. pop() : Removes last elements of the list

# Python Example: use list as stack

# Declare a list named as "stack"


stack = [10, 20, 30]

print ("stack elements: ");

print (stack)

# push operation

stack.append(40)

stack.append(50)

print ("Stack elements after push opration...");

print (stack)

# push operation

print (stack.pop (), " is removed/popped...")

print (stack.pop (), " is removed/popped...")

print (stack.pop (), " is removed/popped...")

print ("Stack elements after pop operation...");

print (stack)

Output

stack elements:

[10, 20, 30]

Stack elements after push opration...

[10, 20, 30, 40, 50]

50 is removed/popped...

40 is removed/popped...

30 is removed/popped...

Stack elements after pop operation...

[10, 20]
Queue

A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends
hence we can easily add elements to the back and can remove elements from the front.

To implement a queue, we need two simple operations:

o enqueue - It adds an element to the end of the queue.

o dequeue - It removes the element from the beginning of the queue.

Operations on Queue
o Addition - It adds the element in a queue and takes place at the rear end, i.e., at the
back of the queue.

o Deletion - It consists of two conditions - If no element is present in the queue,


Underflow occurs in the queue, or if a stack contains some elements then element
present at the front gets deleted.

o Traversing - It involves to visit each element of the queue.

Characteristics

o Insertion order of the queue is preserved.

o Duplicacy is allowed.

o Useful for parsing CPU task operations.

Code

import queue

# Queue is created as an object 'L'

L = queue.Queue(maxsize=10)

# Data is inserted in 'L' at the end using put()

L.put(9)

L.put(6)

L.put(7)

L.put(4)

# get() takes data from

# from the head

# of the Queue

print(L.get())

print(L.get())

print(L.get())
print(L.get())

Output:

List Comprehension

List Comprehension is defined as an elegant way to define, create a list in Python and
consists of brackets that contains an expression followed by for clause. It is efficient in both
computationally and in terms of coding space and time.

Signature

The list comprehension starts with '[' and ']'.

[ expression for item in list if conditional ]

Example

letters = []

for letter in 'Python':

letters.append(letter)

print(letters)

Output:

['P', 'y', 't', 'h', 'o', 'n']

Example

letters = [ letter for letter in 'Python' ]

print( letters)

Output:

['P', 'y', 't', 'h', 'o', 'n']


Looping in lists

There are multiple ways through which we can iterate the list in python programming.

Using for loop

The easiest method to iterate the list in python programming is by using them for a loop. The
method of the iterating list using for loop is as given below

list = [1, 2, 3, 4, 5]

# Iterating list using for loop

for i in list:

print(i)

output

Using range() function

Another method to iterate the list while programming in python is by using the loop and
range() function together. Iterating the list using this method is not recommended if iteration
using for loop(method 1) is possible. The method to do so is as given below:

list = [1, 2, 3, 4, 5]

# getting length of list using len() function

length = len(list)

# using for loop along with range() function

for i in range(length):

print(list[i])
output

Using enumerate() function

There are few times when you may need the display the index of the element along with the
element in the list itself. In such cases, we use the enumerate() function for the iteration of the
list. The method to use the enumerate() function to iterate the list is as given below:

list = [1, 3, 5, 7, 9]

# Using enumerate() function to iterate the list

for i, val in enumerate(list):

print (i, ",",val)

The output of the above code is as given below:

0, 1

1, 3

2, 5

3, 7

4, 9

Using an iterator:

use an iterator to manually loop over the iterable it came from. A repeated passing of iterator
to the built-in function next()returns successive items in the stream. Once, when you
consumed an item from an iterator, it’s gone. When no more data are available
a StopIteration exception is raised.

values = [10, 20, 30]


iterator = iter(values)

print(next(iterator))

print(next(iterator))

print(next(iterator))

Output:

10
20
30

Functional Programming

A programming paradigm that uses functions to define computation is known as functional


programming. The concept of an unchangeable state is one of functional programming’s key
defining traits. In functional programming, higher-order functions are our primary tool for
defining computation. These are functions that take a function as a parameter and return a
function as the result. Reduce(), map(), and filter() are three of Python’s most useful higher-
order functions. They can be used to do complex operations when paired with simpler
functions.

The map() function:

The map() function is a higher-order function. As previously stated, this function accepts
another function and a sequence of ‘iterables’ as parameters and provides output after
applying the function to each iterable in the sequence. It has the following syntax:

SYNTAX: map(function, iterables)

The function is used to define an expression which is then applied to the ‘iterables’. User-
defined functions and lambda functions can both be sent to the map function.

User-defined functions can be sent to the map() method. The user or programmer is the only
one who can change the parameters of these functions.

EXAMPLE

def function(a):

return a*a
x = map(function, (1,2,3,4)) #x is the map object

print(x)

print(set(x))

OUTPUT

{16, 1, 4, 9}

x is a map object, as you can see. The map function is displayed next, which takes
“function()” as a parameter and then applies “a * a” to all ‘iterables’. As a result, all iterables’
values are multiplied by themselves before being returned.

Lambda within map() functions:

Functions with no name are known as lambda functions. These functions are frequently used
as input to other functions. Let’s try to integrate Lambda functions into the map() function.

EXAMPLE

tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61)

newtuple = tuple(map(lambda x: x+3 , tup))

print(newtuple)

OUTPUT

(8, 10, 25, 100, 57, 65, 80, 26, 76, 64)

The filter() function:

The filter() function is used to generate an output list of values that return true when the
function is called. It has the following syntax:

SYNTAX: filter (function, iterables)

This function like map(), can take user-defined functions and lambda functions as parameters.

EXAMPLE

def func(x):

if x>=3:
return x

y = filter(func, (1,2,3,4))

print(y)

print(list(y))

OUTPUT

[3, 4]

Lambda within filter() functions:

The condition to be checked is defined by the lambda function that is provided as an


argument.

EXAMPLE

y = filter(lambda x: (x>=3), (1,2,3,4))

print(list(y))

OUTPUT

[3, 4]

The reduce() function:

The reduce() function applies a provided function to ‘iterables’ and returns a single value, as
the name implies.

SYNTAX: reduce(function, iterables)


The function specifies which expression should be applied to the ‘iterables’ in this case. The
function tools module must be used to import this function.

EXAMPLE

from functools import reduce

reduce(lambda a,b: a+b,[23,21,45,98])

OUTPUT

187

The reduce function in the preceding example adds each iterable in the list one by one and
returns a single result. The Python functions map(), filter(), and reduce() can all be used
together.

Tuples

A Python tuple is an immutable ordered sequence of items. In other words, existing objects in
the sequence cannot be modified, and new elements cannot be added once the sequence is
created. A tuple consists of several values separated by commas. Unlike a Python list, tuples
are enclosed within parentheses “( )”.

Create a Python Tuple

A Python tuple is created by using parentheses separated by commas. A tuple can hold
multiple data types.

Syntax: tuple_name = (“element1”, “element2”, “element3”)

# number tuple # string tuple


number_tuple = (10, 20, 25.75) string_tuple = ('Jessa', 'Emma', 'Kelly')
print(number_tuple) print(string_tuple)
Output (10, 20, 25.75) Output ('Jessa', 'Emma', 'Kelly')
# mixed type tuple # create a tuple using tuple() constructor
sample_tuple = ('Jessa', 30, 45.75, [25, 78]) sample_tuple2 = tuple(('Jessa', 30, 45.75,
print(sample_tuple) [23, 78]))
# Output ('Jessa', 30, 45.75, [25, 78]) print(sample_tuple2)
# without comma # Output ('Jessa', 30, 45.75, [23, 78])
single_tuple = ('Hello') # with comma
print(type(single_tuple)) single_tuple1 = ('Hello',)
Output class 'str' print(type(single_tuple1))
tuple1 = 1, 2, "Hello" Output class ‘tuple’
# display tuple i, j, k = tuple1
print(tuple1) # printing the variables
# Output (1, 2, 'Hello') print(i, j, k)
print(type(tuple1)) # Output 1 2 Hello
# Output class 'tuple'
Utility of tuple:

Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is
the same as returning multiple values. For example, if you want to divide two integers and
compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better
to compute them both at the same time.

The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder. You can store the result as a tuple:

>>> t = divmod(7, 3)

>>> print t

(2, 1)

Or use tuple assignment to store the elements separately:

>>> quot, rem = divmod(7, 3)

>>> print quot

>>> print rem

Accessing values in a tuple

You can access items of a tuple using index just like a list. Provide an index in square
brackets next to the reference to the tuple, and it returns the item in tuple present at the index.

Index of first element is zero, and the index of second element is one.
Slicing operation in tuples

my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)

print(my_data)

# elements from 3rd to 5th

# prints (33, 44, 55)

print(my_data[2:5])

# elements from start to 4th

# prints (11, 22, 33, 44)

print(my_data[:4])

# elements from 5th to end

# prints (55, 66, 77, 88, 99)

print(my_data[4:])

# elements from 5th to second last

# prints (55, 66, 77, 88)

print(my_data[4:-1])

# displaying entire tuple

print(my_data[:])

Output:

(11, 22, 33, 44, 55, 66, 77, 88, 99)

(33, 44, 55)

(11, 22, 33, 44)

(55, 66, 77, 88, 99)

(55, 66, 77, 88)

(11, 22, 33, 44, 55, 66, 77, 88, 99)


Updating tuples:

In tuples we can not update or change the value, because tuples are immutable means can't
change or modifie but only can be updated if their are more then one tuple. Only we take
portions of existing tuples to create a new tuples.

tuple1 = (10, 30.16);

tuple2 = ('abcd', 'xyzp);

#Now i have to create new tupples as follows:

tuple3 = tuple1+tuple2

print tuple3

Output:

(10, 30.16, 'abcd', 'xyzp')

Deleting elements in tuple:

Since tuple is an immutable data structure , you cannot delete the elements from the tuple.
Ofcourse you can create a new tuple that has all the elements in your tuple except the ones
you don’t want.

Delete single element of tuple

#delete single element

number=(1,2.5,1.2,3)

del (number[0])

print(number)

Output

Traceback (most recent call last):


File “”, line 1, in
del (number[0])
TypeError: ‘tuple’ object doesn’t support item deletion

In the above Example , we are deleting element [0] of tuple variable ‘number’ by del
(number[0]) so in output ,we got type error i.e. ‘tuple’ object doesn’t support item deletion.
Example (2): Delete multiple element of tuple

#delete multiple element

alphabet=('a','b','c','d','e')

del(alphabet[1:3])

print(alphabet[1:3])

Output

Traceback (most recent call last):


File “”, line 1, in
del(alphabet[1:3])
TypeError: ‘tuple’ object doesn’t support item deletion

In the above Example , we are deleting multiple element as 1st ,2nd and 3rd index in alphabet
by ‘del(alphabet[1:3])’ so output display the value of 4th and 5th index only as [‘d’, ‘e’].

Example (3): Delete the whole tuple

mytuple=(1,'Python',5.2,'language!')

del (mytuple)

# after deleting tuple

print(mytuple)

Output

Traceback (most recent call last):


File “”, line 1, in
print(mytuple)
NameError: name ‘mytuple’ is not defined

In the above Example , we are deleting tuple variable ‘mytuple’ by del (mytuple) so, we
received the output as error i.e. name ‘mytuple’ is not defined because ‘mytuple’ is already
deleted in the previous step.
TUPLE ASSIGNMENT

An assignment to all of the elements in a tuple using a single assignment statement.


Python has a very powerful tuple assignment feature that allows a tuple of variables on the
left of an assignment to be assigned values from a tuple on the right of the assignment.

The left side is a tuple of variables; the right side is a tuple of values.

Each value is assigned to its respective variable.

All the expressions on the right side are evaluated before any of the assignments. This feature
makes tuple assignment quite versatile.

Naturally, the number of variables on the left and the number of values on the right have to
be the same.

>>> (a, b, c, d) = (1, 2, 3)

ValueError: need more than 3 values to unpack

Example:

-It is useful to swap the values of two variables. With conventional assignment statements,
we have to use a temporary variable. For example, to swap a and b:

Swap two numbers

a=2;b=3

print(a,b)

temp = a

a=b

b = temp

print(a,b)

Output:

(2, 3)

(3, 2)

>>>

-Tuple assignment solves this problem neatly:


(a, b) = (b, a)

-One way to think of tuple assignment is as tuple packing/unpacking.

In tuple packing, the values on the left are ‘packed’ together in a tuple:

>>> b = ("George", 25, "20000") # tuple packing

-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names
on the right:

>>> b = ("George", 25, "20000") # tuple packing

>>> (name, age, salary) = b # tuple unpacking

>>> name

'George'

>>> age

25

>>> salary

'20000'

-The right side can be any kind of sequence (string,list,tuple)

Example:

-To split an email address in to user name and a domain

>>> mailid='[email protected]'

>>> name,domain=mailid.split('@')

>>> print name

god

print (domain)

abc.org

tuples for returning multiple values in python


The most common approach to returning multiple values from a function in Python is using a
Tuple. The idea is to pack values to be returned in a tuple, return the tuple from the function
and unpack it inside the caller function.

This is a preferred approach when you need to return just two or three fields from a function.
The following example shows how you can use tuples to return two fields of different types
from a function.

>>> def function():

a=10; b=10

return a,b

>>> x=function()

>>> type(x)

<class 'tuple'>

>>> x

(10, 10)

>>> x,y=function()

>>> x,y

(10, 10)

In Python, a tuple written inside another tuple is known as a nested tuple. Let’s consider a
tuple having 7 elements as shown below.

tup = ( 10, 20, 30, 40, 50, 60, (100, 200, 300))

#Python code

tup = ( 10, 20, 30, 40, 50, 60, (100, 200, 300))

print('Nested tuple : ', tup[6])

print('Nested tuple element : ',tup[6][1])

The output of this code will be

Nested tuple : (100, 200, 300)


Nested tuple element : 200

Storing records in nested tuple

Each nested tuple can represent a specific data record. For instance, records of many students
consisting RollNo, Name and Aggregate can be stored in a nested tuple as depicted below.
#Python code to store records

StdRec = ((115,'Kriyansh',485),(114,'Arvind', 460),(113,'Sruti ',486), (116,

'Krishant', 480),(111, 'Swati ', 490),(112,'Ishwarya', 489))

print('S. No.', 'RollNo','\t Name','\tAggregate')

for i in range(len(StdRec)):

print(i+1,'\t',StdRec[i][0],'\t',StdRec[i][1],'\t',StdRec[i][2])

The output of this code will be

S. No. RollNo Name Aggregate

1 115 Kriyansh 485

2 114 Arvind 460

3 113 Sruti 486

4 116 Krishant 480

5 111 Swati 490

6 112 Ishwarya 489

Tuple count() method:

Python tuple count() is an inbuilt method that helps us to calculate the occurrence of one
element present in the tuple and returns the counted number. The count() method searches the
given component of a tuple and returns how many times the item has occurred in it. The
count() function returns the number of times the specified value appears in the tuple.

Syntax

tuple.count(element)

vowels = ('a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o')
# count element 'a'

count = vowels.count('a')

# print count

print('The count of a is:', count)

# count element 'k'

count = vowels.count('k')

# print count

print('The count of k is:', count)

Output

The count of a is: 2

The count of k is: 0

In the above code, a character appears 2 times, so it returns 2, and k is not in the tuple so, it
returns 0.

Python Tuple index() Method

Python index() method is used to find the first occurrence of the specified value in the given
input tuple. It raises an exception if the specified value is not found.

Syntax:

tuple.index(value)

Parameter Values

Parameter Description

value This is a required parameter. It defines the item to search for.

Here is an example of Python index() method:

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = thistuple.index(8)

print(x)
Output:
3

Example 2:

a = ['Abhi', 'Mickey', 'Jerry', 'Abhi', 'Cobra', 'Alpha', 'Abhi']

X = a.index("Jerry")

print(X)

Output:
2

list comprehension and tuple

A tuple comprehension is considered to be less fundamental than a list comprehension. So


there is no special syntax dedicated for the same. Yet, if you want a tuple after applying
comprehension, it can be achieved by wrapping tuple() function to perform list
comprehension first and then convert it into a tuple.

tuple1 = (10,6,45,89,90,1,225,76)

tuple2 = tuple([i for i in tuple1 if i%5 == 0])

# Here, we store the output of the comprehension into a list and then explicitly convert it into
a tuple.Printing tuple2 and its type:

print(tuple2)

print(type(tuple2))

Output:

(10, 45, 90, 225)

<class 'tuple'>

Variable-length argument tuples

Functions can take a variable number of arguments. A parameter name that begins
with * gathers arguments into a tuple. For example, printall takes any number of arguments
and prints them:

def printall(*args):
print args

The gather parameter can have any name you like, but args is conventional. Here’s how the
function works:

>>> printall(1, 2.0, '3')

(1, 2.0, '3')

The complement of gather is scatter. If you have a sequence of values and you want to pass
it to a function as multiple arguments, you can use the * operator. For example, divmod takes
exactly two arguments; it doesn’t work with a tuple:

>>> t = (7, 3)

>>> divmod(t)

TypeError: divmod expected 2 arguments, got 1

But if you scatter the tuple, it works:

>>> divmod(*t)

(2, 1)

Exercise 1 Many of the built-in functions use variable-length argument tuples. For
example, max and min can take any number of arguments:

>>> max(1,2,3)

But sum does not.

>>> sum(1,2,3)

TypeError: sum expected at most 2 arguments, got 3

zip() function

Python’s zip() function is defined as zip(*iterables). The function takes in iterables as


arguments and returns an iterator. This iterator generates a series of tuples containing
elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples,
dictionaries, sets, and so on.If you call zip() with no arguments, then you get an empty list in
return.
>>> numbers = [1, 2, 3]
>>> letters = ['a', 'b', 'c']
>>> zipped = zip(numbers, letters)
>>> zipped # Holds an iterator object
<zip object at 0x7fa4831153c8>
>>> type(zipped)
<class 'zip'>
>>> list(zipped)
[(1, 'a'), (2, 'b'), (3, 'c')]

Here, you use zip(numbers, letters) to create an iterator that produces tuples of the form (x, y)

Advantages of Tuples in Python over Lists

The main difference between Python tuples and lists is that the elements of a tuple cannot be
changed once they are assigned; whereas, the elements of a list can be changed.

As tuples and lists are quite similar to each other, they are often used in similar kinds of
situations. Although, a tuple in Python has a bunch of advantages over lists. Following are
some of the main advantages:

• Iteration in a tuple is faster as compared to lists since tuples in Python are immutable.

• Tuples are generally used for different Python Data Types; whereas, lists are used for
similar data types.

• Whenever, we need to make sure that the data remains unchanged and write
protected, Python tuple is the best option.

• Tuples can be used as dictionary keys, because they contain immutable values like
strings, numbers, etc.

• Tuples are fined size in nature i.e. we can’t add/delete elements to/from a tuple.

• Tuple being immutable requires less memory space as compared to list.


• A tuple can be converted to set.
• Tuples are used to format strings
• Multiple values from a function can be returned using a tuple

Sets
A set is an unordered collection data type with no duplicate elements. Sets are iterable
and mutable. The elements appear in an arbitrary order when sets are iterated.

Sets are commonly used for membership testing, removing duplicates entries, and also
for operations such as intersection, union, and set difference.

How to create Sets

Sets can be created by calling the built-in set() function with a sequence or another
iterable object.

>>> #creating an empty set

>>> setA = set()

>>> print(setA)

set()

>>> # creating a set with a string.

>>> # since a string is an iterable, this will succeed.

>>> setA = set("HackerEarth")

>>> print(setA)

{'h', 'H', 't', 'k', 'e', 'c', 'E', 'a', 'r'}

>>> # creating a set with a list

>>> setA = set(["C", “C++”, “Python”])

>>> print(setA)

{'C', 'Python', 'C++'}

>>> # creating a set with a list of numbers


>>> # there are some duplicates in it.

>>> setA = set([1, 2, 3, 4, 5, 6, 7, 7, 7])

>>> print(setA)

{1, 2, 3, 4, 5, 6, 7}

>>> # creating a set with a string. The string has some repeated characters.

>>> myString = 'foobar'

>>> setA = set(myString)

>>> print(setA)

{'r', 'a', 'b', 'f', 'o'}

Methods of set class

Even though mutable objects are not stored in a set, set itself is a mutable object. A set
object can be modified by add(), update(), remove() and discard() methods.

add() Add an element to a set.This has no effect if the element is already


present.

Remove and return an arbitrary set element.RaisesKeyError if the set


pop()
is empty.

Remove an element from a set.If the element is not a member, raise a


remove()
KeyError.

Remove an element from a set if it is a member.If the element is not


discard()
a member, do nothing.

update() Update a set with the union of itself and others.

>>>s1={"Django", "Flask", "Pyramid"}

>>>Print(s1)
Output

{'Django', 'Flask', 'Pyramid'}

>>>s1.add("Turbogears")

>>>print(s1)

Output

{'Django', 'Flask', 'Pyramid', 'Turbogears'}

>>>s2={"NumPy", "SciPy","IPython"}

>>>s1.update(s2)

Output

{'Django', 'Flask', 'IPython', 'NumPy', 'Pyramid', 'SciPy', 'Turbogears'}

The remove(), pop() and discard() methods drop an item from the set. pop() method
drops a random item whereas remove() and discard() need an item to be dropped as
argument. If not present in the set, remove() method raises KeyError exception.

>>>s1.remove('SciPy')

>>>print(s1)

Output

{'Django', 'Flask', 'IPython', 'NumPy', 'Pyramid', 'Turbogears'}

>>>s1.remove("Kivy")

KeyError Traceback (most recent call last)

KeyError: 'Kivy'

>>>s1.pop()
'Flask'

Output:

{'Django', 'IPython', 'NumPy', 'Pyramid', 'Turbogears'}

s1.discard("Flask")

s1

Output

{'Django', 'IPython', 'NumPy', 'Pyramid', 'Turbogears'}

Methods for Set operations:

As mentioned earlier, set data type in Python implements set as defined in mathematics.
Various Set operations like union, intersection, difference and symmetric difference can
be performed using Python’s set object.

Set operations can be summarized by following table:

Union of two sets is a set


of all elements in both.
Union

Intersection of two sets is


Intersection a set containing elements
common to both

Difference of two sets


results in a set containing
Difference
elements only in first but
not in second set.
Result of Symmetric
difference is a set
Symmetric
consisting of elements in
difference
both sets excluding
common elements

Following methods in set class perform above operations:

Return the difference of two or more sets as a new


difference()
set.

difference_update() Remove all elements of another set from this set.

intersection() Return the intersection of two sets as a new set.

Update a set with the intersection of itself and


intersection_update()
another.

Return the symmetric difference of two sets as a new


symmetric_difference()
set.

Update a set with the symmetric difference of itself


symmetric_difference_update()
and another.

union() Return the union of sets as a new set

>>>s1={10,20,30,40,50}

>>>s2=set('abcde')

>>>s3=s1.union(s2)

>>>print(s3)

Output:

{10, 20, 30, 40, 50, 'a', 'b', 'c', 'd', 'e'}

>>>s1={10,20,30,40,50}
>>>s2={0,20,40,60}

>>>s3=s1.intersection(s2)

>>>print(s3)

Output

{20, 40}

>>>s1={10,20,30,40,50}

>>>s2={0,20,40,60}

>>>s3=s1.difference(s2)

>>>print(s3)

Output:

{10, 30, 50}

>>>s1={10,20,30,40,50}

>>>s2={0,20,40,60}

>>>s3=s1.symmetric_difference(s2)

>>>print(s3)

Output

{0, 10, 30, 50, 60}

Above methods (union, intersection, difference and symmetric_difference) return a new


set object. As against these methods intersection_update, difference_update and
symmetric_difference_update perform their respective operations in place. It means
s1.intersection_update(s2) will change s1 to the result of intersection with s2.
>>>s1={10,20,30,40,50}

>>>s2={20,40}

>>>s1.difference_update(s2)

>>>print(s1)

Output

{10, 30, 50}

>>>s1={10,20,30,40,50}

>>>s2={0,20,40,60}

>>>s1.symmetric_difference_update(s2)

>>>print(s1)

Output

{0, 10, 30, 50, 60}

>>>s1={10,20,30,40,50}

>>>s2={0,20,40,60}

>>>s1.intersection_update(s2)

>>>print(s1)

Output

{20, 40}

Boolean set methods

Following methods decide whether a set is a super set, sub set or two are disjoint.
isdisjoint() Return True if two sets have a null intersection.

issubset() Report whether another set contains this set.

issuperset() Report whether this set contains another set.

s1={10,20,30,40,50}

s2={20,40}

s2.issubset(s1)

s1.issuperset(s2)

s1.isdisjoint(s2)

s2.isdisjoint(s1)

Output

True

True

False

False

clear() method drops all items in the set keeping object intact. The del keyword on the
other hand removes object from memory.

s1.clear()

s1

Output

set()

del s2
s2

---------------------------------------------------------------------------

NameError Traceback (most recent call last)

<ipython-input-42-9b4ca538b1cf> in <module>()

1 del s2

----> 2 s2

NameError: name 's2' is not defined

Dictionaries

The data type dictionary fall under mapping. It is a mapping between a set of keys and a
set of values. The key-value pair is called an item. A key is separated from its value by a
colon(:) and consecutive items are separated by commas. Items in dictionaries are
unordered, so we may not get back the data in the same order in which we had entered
the data initially in the dictionary.

Creating a Dictionary

To create a dictionary, the items entered are separated by commas and enclosed in curly
braces. Each item is a key value pair, separated through colon (:). The keys in the
dictionary must be unique and should be of any immutable data type, i.e., number, string
or tuple. The values can be repeated and can be of any data type.

Example

#dict1 is an empty Dictionary created

#curly braces are used for dictionary

>>> dict1 = {}

>>> dict1
{}

#dict2 is an empty dictionary created using

#built-in function

Removing items from the dictionary

There are several methods to remove items from the dictionary. Whether we want to
remove the single item or the last inserted item or delete the entire dictionary, we can
choose the method to be used.

Use the following dictionary methods to remove keys from a dictionary.

Method Description

Return and removes the item with the key and return its value. If
pop(key[,d])
the key is not found, it raises KeyError.

Return and removes the last inserted item from the dictionary. If the
popitem()
dictionary is empty, it raises KeyError.

del key The del keyword will delete the item with the key that is passed

clear() Removes all items from the dictionary. Empty the dictionary

del
Delete the entire dictionary
dict_name

Now, Let’s see how to delete items from a dictionary with an example.

Example

person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50, 'height': 6}

# Remove last inserted item from the dictionary

deleted_item = person.popitem()
print(deleted_item) # output ('height', 6)

# display updated dictionary

print(person)

# Output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50}

# Remove key 'telephone' from the dictionary

deleted_item = person.pop('telephone')

print(deleted_item) # output 1178

# display updated dictionary

print(person)

# Output {'name': 'Jessa', 'country': 'USA', 'weight': 50}

# delete key 'weight'

del person['weight']

# display updated dictionary

print(person)

# Output {'name': 'Jessa', 'country': 'USA'}

# remove all item (key-values) from dict

person.clear()

# display updated dictionary

print(person) # {}

# Delete the entire dictionary


del person

Output

('height', 6)

{'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50}

1178

{'name': 'Jessa', 'country': 'USA', 'weight': 50}

{'name': 'Jessa', 'country': 'USA'}

{}

Sort dictionary

The built-in method sorted() will sort the keys in the dictionary and returns a sorted list.
In case we want to sort the values we can first get the values using the values() and then
sort them.

Example

dict1 = {'c': 45, 'b': 95, 'a': 35}

# sorting dictionary by keys

print(sorted(dict1.items()))

# Output [('a', 35), ('b', 95), ('c', 45)]

# sort dict eys

print(sorted(dict1))

# output ['a', 'b', 'c']

# sort dictionary values


print(sorted(dict1.values()))

# output [35, 45, 95]

Nested dictionary

Nested dictionaries are dictionaries that have one or more dictionaries as their members.
It is a collection of many dictionaries in one dictionary.

Let us see an example of creating a nested dictionary ‘Address’ inside a ‘person’


dictionary.

Example

# address dictionary to store person address

address = {"state": "Texas", 'city': 'Houston'}

# dictionary to store person details with address as a nested dictionary

person = {'name': 'Jessa', 'company': 'Google', 'address': address}

# Display dictionary

print("person:", person)

# Get nested dictionary key 'city'

print("City:", person['address']['city'])

# Iterating outer dictionary

print("Person details")

for key, value in person.items():

if key == 'address':

# Iterating through nested dictionary


print("Person Address")

for nested_key, nested_value in value.items():

print(nested_key, ':', nested_value)

else:

print(key, ':', value)

Output

person: {'name': 'Jessa', 'company': 'Google', 'address': {'state': 'Texas', 'city': 'Houston'}}

City: Houston

Person details

name: Jessa

company: Google

Person Address

state: Texas

city : Houston

Dictionary Methods and Built-in Functions

Python provides many functions to work on dictionaries. Table lists some of the commonly
used dictionary methods.

len() Returns the length or >>> dict1 = 4


number of key: value {'Mohan':95,'Ram':89,
pairs of the dictionary 'Suhel':92, 'Sangeeta':85}
passed as the argument >>> len(dict1)
dict() Creates a dictionary pair1 = {'Mohan': 95, 'Ram':
from a sequence of key- [('Mohan',95),('Ram',89), 89, 'Suhel': 92,
value pairs ('Suhel',92),('Sangeeta',85)] 'Sangeeta': 85}
>>> dict1 = dict(pair1)
>>> dict1
keys() Returns a list of keys in >>> dict1 = {'Mohan':95, (['Mohan', 'Ram',
the dictionary 'Ram':89, 'Suhel':92, 'Suhel', 'Sangeeta'])
'Sangeeta':85}
>>> dict1.keys() dict_keys
values() Returns a list of values >>> dict1 = {'Mohan':95, dict_values([95, 89,
in the dictionary 'Ram':89, 'Suhel':92, 92, 85])
'Sangeeta':85}
>>> dict1.values()
items() Returns a list of tuples >>> dict1 = {'Mohan':95, dict_items([( 'Mohan',
(key — value) pair 'Ram':89, 'Suhel':92, 95), ('Ram', 89),
'Sangeeta':85} ('Suhel', 92),
>>> dict1.items() ('Sangeeta', 85)])
get() Returns the value >>> dict1 = {'Mohan':95, 85
corresponding to the key 'Ram':89, 'Suhel':92, >>>
passed as the argument 'Sangeeta':85}
If the key is not present >>> dict1.get('Sangeeta')
in the dictionary it will >>> dict1.get('Sohan')
return None
update() appends the key-value >>> dict1 = {'Mohan':95, {'Mohan': 95, 'Ram':
pair of the dictionary 'Ram':89, 'Suhel':92, 89, 'Suhel': 92,
passed as the argument 'Sangeeta':85} 'Sangeeta': 85, 'Sohan':
to the key-value pair of >>> dict2 = 79, 'Geeta': 89}
the given dictionary {'Sohan':79,'Geeta':89}
>>> dict1.update(dict2)
>>> dict1
clear() Deletes or clear all the >>> dict1 = {}
items of the dictionary {'Mohan':95,'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> dict1.clear()
>>> dict1
del() Deletes the item with >>> dict1 = {'Mohan':95,'Suhel':92,
the given key To delete {'Mohan':95,'Ram':89, 'Sangeeta': 85}
the dictionary from the 'Suhel':92, 'Sangeeta':85} NameError: name
memory we write: del >>> del dict1['Ram'] 'dict1' is not defined
Dict_name >>> dict1
>>>del dict1
>>>dict1
Difference Between List and Dictionary in Python

Here are the differences present between List and Dictionary in Python:

Parameters List Dictionary

Basics A list refers to a collection of A dictionary refers to a hashed structure


various index value pairs like that of various pairs of keys and values.
in the case of an array in C++.

Creation We can create a list by placing all We can create a dictionary by placing all
the available elements into a [ ] the available elements into a { } in the
and separating them using “,” form of a key:vale. Here, we have to
commas. separate each pair of available key-values
using the “,” commas.

Data Type The indices in the case of a list The keys present in a dictionary can easily
are basically integers that start be of any given data type.
from the value 0.

Mode of We can access the elements in a We can access the elements present in a
Accessing key using indices. dictionary using the key-values.
Order of The entered order of elements is We don’t have any guarantee of
Elements always maintained. maintaining the order of the available
elements.

Classes and objects

Introduction

Till now we have been using the procedure oriented technique in which our
program is written using functions or blocks of statements which manipulate data
however another and infect a better style of programming is called object oriented
programming in which data and functions are combined to form a class compared with
other programming languages python has a very short simple way to define and use
classes and objects.

Classes and objects

Classes and objects are the two main aspects of object oriented programming. In
fact class is a basic building block in python. class creates a new type and object is an
instance or variable of the class. classes provides a blueprint or a template using which
objects are created. In fact in python everything is an object or an instance of some class.
for example all integer variables that we define in our program actual instance of class
int, similarly all string variables are objects of class string.

Creating a Python Class

Just as a function in Python is defined using the def keyword, a class in Python is also
defined using the class keyword, followed by the class name.

Class <classname>:

Statement1

Statement2


Statement_n

the class definition with the class keyword, followed by the class name and a colon(;)
statement in the definition can be any of these-sequential instructions. decision control
statements, loop statements and can even include function definitions. Variables defined
in a class are called class variables and functions defined inside a class are called class
methods.class variables and class methods are together called as class members. Class
members are accessed through class objects

Creating an Object

The object is created after creating a class. Instant of the object is created using the name
same as the class name and it is known as class Instantiation. One can give any name to
a newly created object. Object creation is similar to calling a function. This is because as
soon as the object is created or instantiated with the class name, the default constructor
of the class is called automatically.

Syntax

#object instantiation

object_name = class_name()

Program to access class variable using class object

Class ABC:

Var=10 #class variable

Obj=ABC()

Print(obj.var) #class variable is accessed using class object

Output

10
In above program a class ABC which has a variable var having a value of 10. The object
of the class is created and used to access the class variable using the dot operator.

Data abstraction and hiding through classes

Abstraction is used to hide the internal functionality of the function from the
users. The users only interact with the basic implementation of the function, but inner
working is hidden. User is familiar with that "what function does" but they don't know
"how it does. In simple words, we all use the smartphone and very much familiar with
its functions such as camera, voice-recorder, call-dialing, etc., but we don't know how
these operations are happening in the background. Let's take another example - When
we use the TV remote to increase the volume. We don't know how pressing a key
increases the volume of the TV. We only know to press the "+" button to increase the
volume.In Python, an abstraction is used to hide the irrelevant data/class in order to
reduce the complexity. It also enhances the application efficiency.

Encapsulation is the packing of data and functions that work on that data within a
single object. By doing so, you can hide the internal state of the object from the outside.
This is known as information hiding. A class is an example of encapsulation. A class
bundles data and methods into a single unit. And a class provides the access to its
attributes via methods. The idea of information hiding is that if you have an attribute that
isn’t visible to the outside, you can control the access to its value to make sure your
object is always has a valid state.

Encapsulation offers a way for us to access the required variable without


providing the program full-fledged access to all variables of a class. This mechanism is
used to protect the data of an object from other objects. Encapsulation can be achieved
by declaring the data members and methods of a class either as private or protected. But
In Python, we don’t have direct access modifiers like public, private, and protected. We
can achieve this by using single underscore and double underscores. Access modifiers
limit access to the variables and methods of a class. Python provides three types of
access modifiers private, public, and protected.

Public Member: Accessible anywhere from otside oclass.


Private Member: Accessible within the class

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

Public data members are accessible within and outside of a class. All member
variables of the class are by default public. We can protect variables in the class by
marking them private. To define a private variable add two underscores as a prefix at the
start of a variable name. Private members are accessible only within the class, and we
can’t access them directly from the class objects.

Class method and self argument:

When we create a class in Python, instance methods are used regularly. To work with an
instance method, we use the self keyword. We use the self keyword as the first
parameter to a method. The self refers to the current object. Any method we create in a
class will automatically be created as an instance method unless we explicitly tell
Python that it is a class or static method. Instance variables are not shared between
objects. Instead, every object has its copy of the instance attribute. Using the instance
method, we can access or modify the calling object’s attributes.

Instance methods are defined inside a class, and it is pretty similar to defining a
regular function.

• Use the def keyword to define an instance method in Python.


• Use self as the first parameter in the instance method when defining it.
The self parameter refers to the current object.
• Using the self parameter to access or modify the current object attributes.

You may use a variable named differently for self, but it is discouraged since self is the
recommended convention in Python. We use an object and dot (.) operator to execute the
block of code or action defined in the instance method.

• First, create instance variables name and age in the Student class.
• Next, create an instance method display() to print student name and age.
• Next, create object of a Student class to call the instance method.
Program to access class members using the class object

Class ABC():

Var=10

Def display(self):

Print(“in class method”)

Obj=ABC()

Print(obj.var)

Obj.display()

Output

10

In class method

__init__() method(the class constructor)

Python class constructor function job is to initialize the instance of the class. Python
__init__() is the constructor function for the classes in Python. The __init__() function
syntax is:

def __init__(self, [arguments])

• The def keyword is used to define it because it’s a function.


• The first argument refers to the current object. It binds the instance to the init()
method. It’s usually named “self” to follow the naming convention. You can read
more about it at Python self variable.
• The init() method arguments are optional. We can define a constructor with any
number of arguments.

# class
class Awesome:

# the init method

def __init__(self):

print("Hello from the __init__ method.")

# calling the class method

self.greetings()

# methods

def greetings(self):

print("Hello from the greetings() method.")

# object of the class

obj = Awesome()

The above code will print the following output.

Hello from the __init__ method.

Hello from the greetings() method.

Class variables and object variables

The data part, i.e. fields, are nothing but ordinary variables that are bound to
the namespaces of the classes and objects. This means that these names are valid within
the context of these classes and objects only. That’s why they are called name spaces.

There are two types of fields – class variables and object variables which are classified
depending on whether the class or the object owns the variables respectively.
Class variables are shared – they can be accessed by all instances of that class. There is
only one copy of the class variable and when any one object makes a change to a class
variable, that change will be seen by all the other instances.

Object variables are owned by each individual object/instance of the class. In this case,
each object has its own copy of the field i.e. they are not shared and are not related in
any way to the field by the same name in a different instance.

class Car:

# Class variable

manufacturer = 'BMW'

def __init__(self, model, price):

# instance variable

self.model = model

self.price = price

# create Object

car = Car('x1', 2500)

print(car.model, car.price, Car.manufacturer)

Output:

x1 2500 BMW

Understanding the difference between the Class Variable and Instance Variable

Since we have understood the basic concepts of both the variables and how these
variables are used in the class, let us understand how class variable differs from
the instance variable. The major differences between these two variables are
described in the tabular format shown below:
S. Class Variable Instance Variable
No.

1 A class variable is a variable that An instance variable is a


defines a particular property or variable whose value is
attribute for a class. specified to the Instance and
shared among different
instances.

2 We can share these variables We cannot share these variables


between class and its subclasses. between classes. However, they
only fit in a particular class.

3 It generally supports a single It generally stores memory for


shared value for every instance of data required by the class.
class even if there is no instance
object present in the class.

4 It is usually defined whenever we It is usually defined whenever


begin the execution of the we create an instance of the
program. class.

5 It generally recollects the values It generally recollects the values


until the program ends. as long as the object exists.

6 It has only one replica of the class It has multiple replicas, so each
variable, so it is shared between object has its replica of the
various class objects. instance variable.

7 We can access these variables by We can access these variables


calling with the class name. directly by calling variable
names within the class.
8 We have to declare these variables We have to declare these
with the help of the static variables without utilizing the
keyboard. static keyword.

9 Whatever alterations we made to Whatever alterations we made


these variables via one object will to these variables via one object
be replicated in another object. will not be replicated in another
object.

In Python, destructor is not called manually but completely automatic. destructor gets
called in the following two cases

• When an object goes out of scope or


• The reference counter of the object reaches 0.

In Python, The special method __del__() is used to define a destructor. For example,
when we execute del object_name destructor gets called automatically and the object
gets garbage collected.

The magic method __del__() is used as the destructor in Python. The __del__() method
will be implicitly invoked when all references to the object have been deleted, i.e., is
when an object is eligible for the garbage collector.

This method is automatically called by Python when the instance is about to be


destroyed. It is also called a finalizer or (improperly) a destructor.

Syntax of destructor declaration

def __del__(self):

# body of a destructor

Where,

• def: The keyword is used to define a method.


• __del__() Method: It is a reserved method. This method gets called as soon as all
references to the object have been deleted
• self: The first argument self refers to the current object.

Note: The __del__() method arguments are optional. We can define a destructor with
any number of arguments.

class Student:

# constructor

def __init__(self, name):

print('Inside Constructor')

self.name = name

print('Object initialized')

def show(self):

print('Hello, my name is', self.name)

# destructor

def __del__(self):

print('Inside destructor')

print('Object destroyed')

# create object

s1 = Student('Emma')

s1.show()

# delete object

del s1

Output
Inside Constructor

Object initialized

Hello, my name is Emma

Inside destructor

Object destroyed

Special Class Methods

Public and Private Data Members

The variables which are defined inside the class is public by default. These variables can
be accessed anywhere in the program using dot operator.

A variable prefixed with double underscore becomes private in nature. These variables
can be accessed only within the class.

Example : Program to illustrate private and public variables

class Sample:

def __init__(self, n1, n2):

self.n1=n1

self.__n2=n2

def display(self):

print("Class variable 1 = ", self.n1)

print("Class variable 2 = ", self.__n2)


S=Sample(12, 14)

S.display()

print("Value 1 = ", S.n1)

print("Value 2 = ", S.__n2)

In the above program, there are two class variables n1 and n2 are declared. The variable
n1 is a public variable and n2 is a private variable. The display( ) member method is
defined to show the values passed to these two variables.

The print statements defined within class will successfully display the values of n1 and
n2, even though the class variable n2 is private. Because, in this case, n2 is called by a
method defined inside the class. But, when we try to access the value of n2 from outside
the class Python throws an error. Because, private variable cannot be accessed from
outside the class.

Output

Class variable 1 = 12

Class variable 2 = 14

Value 1 = 12

Traceback (most recent call last):

File "D:/Python/Class-Test-04.py", line 12, in <module> print("Value 2 = ", S.__n2)

AttributeError: 'Sample' object has no attribute '__n2

Private methods

Private methods are such methods that cannot be accessed outside a class definition. In
the real world, if something is private to us, other people aren’t supposed to have access
to that. Similarly, We are not supposed to access the private methods defined inside a
class.
Python doesn’t support private methods. But, we can simulate the implementation of
private methods in python. For that, we have to define the name of the private method
using two underscore signs as follows.

def __methodName():

pass

Here, we have used the def keyword to define the method and the pass keyword has
been used to create a method body that does nothing.

# Creating a class

class A:

# Declaring public method

def fun(self):

print("Public method")

# Declaring private method

def __fun(self):

print("Private method")

# Driver's code

obj = A()

# Calling the private member

# through name mangling

obj._A__fun()

Output:
Private method

calling a class method from another class method in python

we can call the method of another class by using their class name and function with dot
operator.
for Example:-
if the 1st class name is class A and its method is method_A
and the second class is class B and its method is method_B

A stack data structure is used during the execution of the function calls. Whenever a
function is invoked then the calling function is pushed into the stack and called function
is executed. When the called function completes its execution and returns then the
calling function is popped from the stack and executed. Calling Function execution will
be completed only when called Function is execution completes.

# Python code to demonstrate calling the

# function from another function

def Square(X):

# computes the Square of the given number


# and return to the caller function

return (X * X)

def SumofSquares(Array, n):

# Initialize variable Sum to 0. It stores the

# Total sum of squares of the array of elements

Sum = 0

for i in range(n):

# Square of Array[i] element is stored in SquaredValue

SquaredValue = Square(Array[i])

# Cumulative sum is stored in Sum variable

Sum += SquaredValue

return Sum

# Driver Function

Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

n = len(Array)

# Return value from the function

# Sum of Squares is stored in Total

Total = SumofSquares(Array, n)

print("Sum of the Square of List of Numbers:", Total)

Output :
Sum of the Square of List of Numbers: 385

built in functions to get set check and delete class attributes

Attributes of a class are function objects that define corresponding methods of its
instances. They are used to implement access controls of the classes.
Attributes of a class can also be accessed using the following built-in methods and
functions :

1. getattr() – This function is used to access the attribute of object.


2. hasattr() – This function is used to check if an attribute exist or not.
3. setattr() – This function is used to set an attribute. If the attribute does not exist,
then it would be created.
4. delattr() – This function is used to delete an attribute. If you are accessing the
attribute after deleting it raises error “class has no attribute”.

The following methods are explained with the example given below :

# Python code for accessing attributes of class

class emp:

name='Harsh'

salary='25000'

def show(self):

print (self.name)

print (self.salary)

e1 = emp()

# Use getattr instead of e1.name


print (getattr(e1,'name'))

# returns true if object has attribute

print (hasattr(e1,'name'))

# sets an attribute

setattr(e1,'height',152)

# returns the value of attribute name height

print (getattr(e1,'height'))

# delete the attribute

delattr(emp,'salary')

Output :

Harsh

True

152

Built-In Class Attributes

Every Python class keeps following built-in attributes and they can be accessed using
dot operator like any other attribute −

• __dict__ − Dictionary containing the class's namespace.


• __doc__ − Class documentation string or none, if undefined.
• __name__ − Class name.
• __module__ − Module name in which the class is defined. This attribute is
"__main__" in interactive mode.
• __bases__ − A possibly empty tuple containing the base classes, in the order of
their occurrence in the base class list.

For the above class let us try to access all these attributes −

class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount += 1

def displayCount(self):

print "Total Employee %d" % Employee.empCount

def displayEmployee(self):

print "Name : ", self.name, ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__

print "Employee.__name__:", Employee.__name__

print "Employee.__module__:", Employee.__module__

print "Employee.__bases__:", Employee.__bases__

print "Employee.__dict__:", Employee.__dict__

When the above code is executed, it produces the following result −

Employee.__doc__: Common base class for all employees


Employee.__name__: Employee

Employee.__module__: __main__

Employee.__bases__: ()

Employee.__dict__: {'__module__': '__main__', 'displayCount':

<function displayCount at 0xb7c84994>, 'empCount': 2,

'displayEmployee': <function displayEmployee at 0xb7c8441c>,

'__doc__': 'Common base class for all employees',

'__init__': <function __init__ at 0xb7c846bc>}

Garbage Collection

Python deletes unneeded objects (built-in types or class instances) automatically to free
the memory space. The process by which Python periodically reclaims blocks of
memory that no longer are in use is termed Garbage Collection.

Python's garbage collector runs during program execution and is triggered when an
object's reference count reaches zero. An object's reference count changes as the number
of aliases that point to it changes.

An object's reference count increases when it is assigned a new name or placed in a


container (list, tuple, or dictionary). The object's reference count decreases when it's
deleted with del, its reference is reassigned, or its reference goes out of scope. When an
object's reference count reaches zero, Python collects it automatically.

a = 40 # Create object <40>

b=a # Increase ref. count of <40>

c = [b] # Increase ref. count of <40>


del a # Decrease ref. count of <40>

b = 100 # Decrease ref. count of <40>

c[0] = -1 # Decrease ref. count of <40>

You normally will not notice when the garbage collector destroys an orphaned instance
and reclaims its space. But a class can implement the special method __del__(), called a
destructor, that is invoked when the instance is about to be destroyed. This method
might be used to clean up any non memory resources used by an instance.

Class Method

The @classmethod decorator is a built-in function decorator that is an expression that


gets evaluated after your function is defined. The result of that evaluation shadows your
function definition.
A class method receives the class as an implicit first argument, just like an instance
method receives the instance
Syntax:

class C(object):

@classmethod

def fun(cls, arg1, arg2, ...):

....

fun: function that needs to be converted into a class method

returns: a class method for function.

• A class method is a method that is bound to the class and not the object of the
class.
• They have the access to the state of the class as it takes a class parameter that
points to the class and not the object instance.
• It can modify a class state that would apply across all the instances of the class.
For example, it can modify a class variable that will be applicable to all the
instances.

Static Method

A static method does not receive an implicit first argument.

Syntax:

class C(object):

@staticmethod

def fun(arg1, arg2, ...):

...

returns: a static method for function fun.

• A static method is also a method that is bound to the class and not the object of
the class.
• A static method can’t access or modify the class state.
• It is present in a class because it makes sense for the method to be present in
class.

Class method vs Static Method

• A class method takes cls as the first parameter while a static method needs no
specific parameters.
• A class method can access or modify the class state while a static method can’t
access or modify it.
• In general, static methods know nothing about the class state. They are utility-
type methods that take some parameters and work upon those parameters. On the
other hand class methods must have class as a parameter.
• We use @classmethod decorator in python to create a class method and we use
@staticmethod decorator to create a static method in python.
The __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.

Use the __init__() function to assign values to object properties, or other operations that
are necessary to do when the object is being created:

Example

Create a class named Person, use the __init__() function to assign values for name and
age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)
print(p1.name)
print(p1.age)

Note: The __init__() function is called automatically every time the class is being used
to create a new object.

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the
object.

Let us create a method in the Person class:

Example

Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Note: The self-parameter is a reference to the current instance of the class, and is used to
access variables that belong to the class.

The self-Parameter

The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class:

Example

Use the words mysillyobject and abc instead of self:

class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

You might also like