python unit 3 (1)
python unit 3 (1)
List in python
A list in Python is used to store the sequence of various types of data.
Python lists are mutable type its mean we can modify its element after it created.
A list can be defined as a collection of values or items of different types.
The items in the list are separated with the comma (,) and enclosed with square brackets [ ].
A list can be define as below
L1 = ["Daksh", 107, "Naksh"]
L2 = [1, 2, 3, 4, 5, 6,7]
We can add one item to a list using the append() method or add several items using the
extend() method.
Example :
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd) #Output : [1, 3, 5, 7]
ANKUR 1
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
We can also use + operator to combine two lists which is also called concatenation.
The * operator repeats a list for the given number of times.
Example :
# Concatenating and repeating lists
odd = [1, 3, 5]
print(odd + [9, 7, 5]) #Output : [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output : ['re', 're', 're']
Further, we can insert one item at a desired location by using the method insert() or insert
multiple items by squeezing it into an empty slice of a list.
Example :
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)
print(odd) #Output : [1, 3, 9]
odd[2:2] = [5, 7]
print(odd) #Output : [1, 3, 5, 7, 9]
ANKUR 2
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
We can use remove() to remove the given item or pop() to remove an item at the given index.
The pop() method removes and returns the last item if the index is not provided.
Example :
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list.pop(1)) # Output: 'o'
print(my_list) # Output: ['r', 'b', 'l', 'e', 'm']
print(my_list.pop()) # Output: 'm'
print(my_list) # Output: ['r', 'b', 'l', 'e']
my_list.clear()
print(my_list) # Output: []
# first item
print(my_list[0]) # Output: p
# third item
print(my_list[2]) # Output: o
ANKUR 3
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
# fifth item
print(my_list[4]) # Output: e
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1]) # Output: a
print(n_list[1][3]) # Output: 5
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.
Example :
# Negative indexing in lists
my_list = ['p','r','o','b','e']
# last item
print(my_list[-1]) # Output: e
# fifth last item
print(my_list[-5]) # Output: p
Example :
# List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
# elements from index 2 to index 4
print(my_list[2:5]) # Output: ['o', 'g', 'r']
# elements from index 5 to end
print(my_list[5:]) # Output: ['a', 'm', 'i', 'z']
# elements beginning to end
print(my_list[:]) # Output: ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
ANKUR 4
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
List Operators
Like the string, the list is also a sequence.
Hence, the operators used with strings are also available for use with the list (and tuple also).
Operator Example
The + operator returns a list containing all the elements of >>> L1=[1,2,3]
the first and the second list. >>> L2=[4,5,6]
>>> L1+L2
[1, 2, 3, 4, 5, 6]
The * operator concatenates multiple copies of the same list. >>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The slice operator [] returns the item at the given index. >>> L1=[1, 2, 3]
A negative index counts the position from the right side. >>> L1[0]
1
>>> L1[-3]
1
>>> L1[1]
2
>>> L1[-2]
2
>>> L1[2]
3
>>> L1[-1]
3
The range slice operator [FromIndex : Untill Index - 1] >>> L1=[1, 2, 3, 4, 5, 6]
fetches items in the range specified by the two index >>> L1[1:]
operands separated by : symbol. [2, 3, 4, 5, 6]
>>> L1[:3]
[1, 2, 3]
>>> L1[3:]
[4, 5, 6]
The in operator returns true if an item exists in the given list. >>> L1=[1, 2, 3, 4, 5, 6]
>>> 4 in L1
True
>>> 10 in L1
False
ANKUR 5
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
The not in operator returns true if an item does not exist in >>> L1=[1, 2, 3, 4, 5, 6]
the given list. >>> 5 not in L1
False
>>> 10 not in L1
True
Output :
[1, 2, 3, 55, 98, 65, 13, 29]
ANKUR 6
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
Output :
The sum is: 67
Iterate List
A list items can be iterate using the for loop.
Example :
names=["Daksh", "Naksh", "Krunal"]
for name in names:
print(name)
Output :
Daksh
Naksh
Krunal
Output :
I like apple
I like banana
I like mango
ANKUR 7
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
tuple in python
Python Tuple is used to store the sequence of immutable Python objects.
The Tuple is similar to lists since the value of the items stored in the list can be changed,
whereas the value of the items stored in the tuple cannot be changed.
Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets.
The parentheses are optional but it is good practice to use.
A tuple can be defined as follows.
T1 = ("Daksh", 107, "Naksh")
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50
ANKUR 8
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
Example :
# Concatenation
print((1, 2, 3) + (4, 5, 6)) # Output: (1, 2, 3, 4, 5, 6)
# Repeat
print(("Repeat",) * 3) # Output: ('Repeat', 'Repeat', 'Repeat')
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple.
It means that we cannot delete or remove items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
Example :
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
ANKUR 9
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(n_tuple[0][3]) # Output: 's'
print(n_tuple[1][1]) # Output: 4
Tuple Operations
Like string, tuple objects are also a sequence. Hence, the operators used with strings are also
available for the tuple.
Operator Example
The + operator returns a tuple containing all the >>> t1=(1,2,3)
elements of the first and the second tuple object. >>> t2=(4,5,6)
>>> t1+t2
(1, 2, 3, 4, 5, 6)
>>> t2+(7,)
(4, 5, 6, 7)
The * operator Concatenates multiple copies of the >>> t1=(1,2,3)
same tuple >>> t1*4
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
The [] operator Returns the item at the given index. >>> t1=(1,2,3,4,5,6)
A negative index counts the position from the right >>> t1[3]
side. 4
>>> t1[-2]
5
ANKUR 10
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
The [:] operator returns the items in the range specified >>> t1=(1,2,3,4,5,6)
by two index operands separated by the : symbol. >>> t1[1:3]
If the first operand is omitted, the range starts from (2, 3)
zero. >>> t1[3:]
If the second operand is omitted, the range goes up to (4, 5, 6)
the end of the tuple. >>> t1[:3]
(1, 2, 3)
The in operator returns true if an item exists in the >>> t1=(1,2,3,4,5,6)
given tuple. >>> 5 in t1
True
>>> 10 in t1
False
The not in operator returns true if an item does not exist >>> t1=(1,2,3,4,5,6)
in the given tuple. >>> 4 not in t1
False
>>> 10 not in t1
True
Tuple Methods
Methods that add items or remove items are not available with tuple.
Only the following two methods named as count() and index() are available.
Example :
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
Output :
Hello Daksh
Hello Naksh
ANKUR 11
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
# In operation
print('a' in my_tuple) # Output: True
print('b' in my_tuple) # Output: False
# Not in operation
print('g' not in my_tuple) # Output:True
ANKUR 12
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
File in python
There are two types of files in Python named as Binary file and Text file
Most importantly there are 4 types of operations that can be handled by Python on files as
Open, Read, Write, Close.
Other operations on file include Rename and Delete.
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Example :
# Create a new file called "myfile.txt":
f = open("myfile.txt", "x")
Example :
# Create a new file if it does not exist:
f = open("myfile.txt", "w")
ANKUR 13
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
If the file is located in a different location, you will have to specify the file path, like this:
Example :
# Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example :
# Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
By calling readline() two times, you can read the two first lines:
Example :
# Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Close Files
It is a good practice to always close the file when you are done with it.
Example :
# Close the file when you are finish with it:
f = open("demofile.txt", "r")
f.close()
ANKUR 14
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
Example :
# Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Example :
# Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example :
# Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
ANKUR 15
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
The class also contains a function display(), which is used to display the information of the
Employee.
Here, the self is used as a reference variable, which refers to the current class object.
Example :
class Employee :
id = 1
name = "Daksh"
def display (self):
print(self.id,self.name)
Object in Python
An Object is an instance of a Class.
A class is like a blueprint while an instance is a copy of the class
The syntax for creating object is : object name = class name
The procedure to create an object is : daksh = Employee()
This will create a new object instance named daksh and we can access the attributes of
objects using the object name prefix.
ANKUR 16
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
Example :
class Employee:
id = 1
name = "Daksh"
output :
ID: 1
Name: Daksh
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("Daksh", 10)
p1.myfunc()
ANKUR 17
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
Output :
ID: 101
Name: Daksh
ID: 102
Name: Naksh
ANKUR 18
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person(Daksh)
p.say_hi()
Output :
Hello, my name is Daksh
ANKUR 19
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
inheritance in Python
The process of inheriting the properties of the parent class into a child class is called
inheritance.
The existing class is called a base class or parent class and the new class is called a subclass
or child class or derived class.
The main purpose of inheritance is the reusability of code because we can use the existing
class to create a new class instead of creating it from scratch.
In inheritance, the child class acquires all the data members, properties, and functions from
the parent class. Also, a child class can also provide its specific implementation to the
methods of the parent class.
For example, In the real world, Car is a sub-class of a Vehicle class. We can create a Car by
inheriting the properties of a Vehicle such as Wheels, Colors, Fuel tank, engine, and add
extra properties in Car as required.
The basic syntax of inheritance is define as below:
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
In Python, based upon the number of child and parent classes involved, there are four types
of inheritance named as Single inheritance, Multiple Inheritance, Multilevel inheritance and
Hierarchical Inheritance.
1. Single Inheritance
In single inheritance, a child class inherits from a single-parent class. Here is one child class
and one parent class.
ANKUR 20
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
Output :
Inside Vehicle class
Inside Car class
2. Multiple Inheritance
In multiple inheritance, one child class can inherit from multiple parent classes. So here is
one child class and multiple parent classes.
ANKUR 21
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
# Parent class 2
class Company:
def company_info(self, company_name, location):
print('Inside Company class')
print('Name:', company_name, 'location:', location)
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)
# access data
emp.person_info('Daksh', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee_info(12000, 'Machine Learning')
Output :
Inside Person class
Name: Daksh Age: 28
ANKUR 22
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
In the above example, we created two parent classes Person and Company respectively.
Then we create one child called Employee which inherit from Person and Company classes.
3. Multilevel inheritance
In multilevel inheritance, a class inherits from a child class or derived class. Suppose three
classes A, B, C.
A is the superclass, B is the child class of A, C is the child class of B.
In other words, we can say a chain of classes is called multilevel inheritance.
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
ANKUR 23
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')
Output :
Inside Vehicle class
Inside Car class
Inside SportsCar class
In the above example, we can see there are three classes named Vehicle, Car, SportsCar.
Vehicle is the superclass, Car is a child of Vehicle, SportsCar is a child of Car. So we can see
the chaining of classes.
4. Hierarchical Inheritance
In Hierarchical inheritance, more than one child class is derived from a single parent class.
In other words, we can say one parent class and multiple child classes.
ANKUR 24
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
# Child class
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)
# Child class
class Truck(Vehicle):
def truck_info(self, name):
print("Truck name is:", name)
obj1 = Car()
obj1.info()
obj1.car_info('BMW')
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
Output :
This is Vehicle
Car name is: BMW
This is Vehicle
Truck name is: Ford
In above example, we declare ‘Vehicle’ as a parent class and two child class ‘Car’ and
‘Truck’
ANKUR 25
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
Encapsulation in Python
Encapsulation in Python describes the concept of bindling data and methods within a single
unit.
A class is an example of encapsulation as it binds all the data members (instance variables)
and methods into a single unit.
Encapsulation is a way to can restrict access to methods and variables from outside of class.
Example :
class Employee:
# constructor
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project
ANKUR 26
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
def work(self):
print(self.name, 'is working on', self.project)
Output :
Name: Daksh Salary: 8000
Daksh is working on NLP
Using encapsulation, we can hide an object’s internal representation from the outside which
is called information hiding.
ANKUR 27
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
Advantages of Encapsulation
Security : The main advantage of using encapsulation is the security of the data.
Encapsulation protects an object from unauthorized access. It allows private and
protected access levels to prevent accidental data modification.
Data Hiding : The user would not be knowing what is going on behind the scene. They
would only be knowing that to modify a data member, call the setter method. To read a
data member, call the getter method. What these setter and getter methods are doing is
hidden from them.
Aesthetics : Bundling data and methods within a class makes code more readable and
maintainable.
ANKUR 28
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
polymorphism in python
Polymorphism in Python is the ability of an object to take many forms.
In simple words, Polymorphism allows us to perform the same action in many different
ways.
For example, Jessa acts as an employee when she is at the office. However, when she is at
home, she acts like a wife. Also, she represents herself differently in different places.
Therefore, the same person takes different forms as per the situation.
In polymorphism, a method can process objects differently depending on the class type or
data type.
The built-in function len() calculates the length of an object depending upon its type.
If an object is a string, it returns the count of characters, and If an object is a list, it returns the
count of items in a list.
The len() method treats an object as per its class type.
Example :
students = ['Emma', 'Jessa', 'Kelly']
school = 'ABC School'
# calculate count
print(len(students)) #output : 3
print(len(school)) #output : 10
ANKUR 29
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
Example :
class Vehicle:
def show(self):
print('Details:', self.name, self.color, self.price)
def max_speed(self):
print('Vehicle max speed is 150')
def change_gear(self):
print('Vehicle change 6 gear')
ANKUR 30
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON
def change_gear(self):
print('Car change 7 gear')
# Car Object
car = Car('Car x1', 'Red', 20000)
car.show()
# Vehicle Object
vehicle = Vehicle('Truck x1', 'white', 75000)
vehicle.show()
Output :
Details: Car x1 Red 20000
Car max speed is 240
Car change 7 gear
ANKUR 31