Python Lists
• In Python, a list is a built-in dynamic sized
array (automatically grows and shrinks). We
can store all types of items (including another
list) in a list.
List can contain duplicate items.
• List in Python are alterable. Hence, we can
modify, replace or delete the items.
• List are ordered. It maintain the order of
elements based on how they are added.
• Accessing items in List can be done directly
using their position (index), starting from 0.
a = [10, 20, 15]
print(a[0]) # access first item
a.append(11) # add item
a.remove(20) # remove item
print(a)
Output
10
[10, 15, 11]
Creating a List
# List of integers
a = [1, 2, 3, 4, 5]
# List of strings
b = ['apple', 'banana', 'cherry']
# Mixed data types
c = [1, 'hello', 3.14, True]
print(a)
print(b)
print(c)
• Output
• [1, 2, 3, 4, 5]
• ['apple', 'banana', 'cherry']
• [1, 'hello', 3.14, True]
Adding Elements into List
• We can add elements to a list using the
following methods:
• append(): Adds an element at the end of the
list.
• extend(): Adds multiple elements to the end
of the list.
• insert(): Adds an element at a specific
position.
# Initialize an empty list
a = []
# Adding 10 to end of list
a.append(10)
print("After append(10):", a)
# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)
# Adding multiple elements [15, 20, 25] at the end
a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", a)
• After append(10): [10]
• After insert(0, 5): [5, 10]
• After extend([15, 20, 25]): [5, 10, 15, 20, 25]
Python Arrays
• In Python, array is a collection of items stored
at contiguous memory locations. The idea is to
store multiple items of the same type together
import array as arr
# creating array of integers
a = arr.array('i', [1, 2, 3])
# accessing First Araay
print(a[0])
# Adding element to array
a.append(5)
print(a)
Output
1
array('i', [1, 2, 3, 5])
Create an Array in Python
• Array in Python can be created by importing
an array module. array( data_type , value_list )
is used to create array in Python with data
type and value list specified in its arguments.
import array as arr
# creating array
a = arr.array('i', [1, 2, 3])
# iterating and printing each item
for i in range(0, 3):
print(a[i], end=" ")
Output
1 2 3
Adding Elements to an Array
• Elements can be added to the Python Array by
using built-in insert() function. Insert is used to
insert one or more data elements into an
array.
import array as arr
# Integer array example
a = arr.array('i', [1, 2, 3])
print("Integer Array before insertion:", *a)
a.insert(1, 4) # Insert 4 at index 1
print("Integer Array after insertion:", *a)
Output
Integer Array before insertion: 1 2 3
Integer Array after insertion: 1 4 2 3
Accessing Array Items
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print(a[0])
print(a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print(b[1])
print(b[2])
Output
1
4
3.2
3.3
Removing Elements from the Array
• Elements can be removed from the Python
array by using built-in remove() function.
import array
arr = array.array('i', [1, 2, 3, 1, 5])
# using remove() method to remove first occurance of 1
arr.remove(1)
print(arr)
# pop() method - remove item at index 2
arr.pop(2)
print(arr)
Output
array('i', [2, 3, 1, 5])
array('i', [2, 3, 5])
Stack and Queues in Python
• Stack works on the principle of “Last-in, first-
out”.
# Python code to demonstrate Implementing
# stack using list
stack = ["Amar", "Akbar", "Anthony"]
stack.append("Ram")
stack.append("Iqbal")
print(stack)
# Removes the last item
print(stack.pop())
print(stack)
# Removes the last item
print(stack.pop())
print(stack)
• Output:['Amar', 'Akbar', 'Anthony', 'Ram',
'Iqbal'] Iqbal
• ['Amar', 'Akbar', 'Anthony', 'Ram'] Ram
• ['Amar', 'Akbar', 'Anthony']
Queue
• works on the principle of “First-in, first-out”.
• # Python code to demonstrate Implementing
• # Queue using list
• queue = ["Amar", "Akbar", "Anthony"]
• queue.append("Ram")
• queue.append("Iqbal")
• print(queue)
• # Removes the first item
• print(queue.pop(0))
• print(queue)
• # Removes the first item
• print(queue.pop(0))
• print(queue)
• Output:['Amar', 'Akbar', 'Anthony', 'Ram',
'Iqbal'] Amar
• ['Akbar', 'Anthony', 'Ram', 'Iqbal'] Akbar
• ['Anthony', 'Ram', 'Iqbal']
Tuples in Python
• Python Tuple is a collection of objects
separated by commas. A tuple is similar to a
Python list in terms of indexing, nested
objects, and repetition but the main
difference between both is Python tuple is
immutable, unlike the Python list which is
mutable.
# Note : In case of list, we use square
# brackets []. Here we use round brackets ()
t = (10, 20, 30)
print(t)
print(type(t))
Output
(10, 20, 30)
<class 'tuple'>
What is Immutable in Tuples?
• Unlike Python lists, tuples are immutable. Some
Characteristics of Tuples in Python.
• Like Lists, tuples are ordered and we can access their
elements using their index values
• We cannot update items to a tuple once it is created.
• Tuples cannot be appended or extended.
• We cannot remove items from a tuple once it is
created.
t = (1, 2, 3, 4, 5)
# tuples are indexed
print(t[1])
print(t[4])
# tuples contain duplicate elements
t = (1, 2, 3, 4, 2, 3)
print(t)
# updating an element
t[1] = 100
print(t)
2
5
(1, 2, 3, 4, 2, 3)
ERROR!
Traceback (most recent call last):
File "<main.py>", line 9, in <module>
TypeError: 'tuple' object does not support item assignment
=== Code Exited With Errors ===
Packing and Unpacking a Tuple
• In Python, there is a very powerful tuple
assignment feature that assigns the right-hand
side of values into the left-hand side. In
another way, it is called unpacking of a tuple
of values into a variable.
# Program to understand about
# packing and unpacking in Python
# this lines PACKS values
# into variable a
a = ("MNNIT Allahabad", 5000, "Engineering")
# this lines UNPACKS values
# of variable a
(college, student, type_ofcollege) = a
# print college name
print(college)
# print no of student
print(student)
# print type of college
print(type_ofcollege)
• Output:
• MNNIT Allahabad
• 5000
• Engineering
Sets
• Set class is used to represent the collection of
elements without duplicates, and without any
inherent order to those elements. It is
enclosed by the {} and each element is
separated by the comma(,) and it is mutable.
# set of alphabet
set = {'a', 'b', 'c', 'd', 'e'}
print(set)
Output:
{'c', 'b', 'd', 'e', 'a'}
Dictionaries
• It is a mapping of different keys to its
associated values. We use curly brackets { } to
create dictionaries too.
# Example of Dictionary
d = {'jupiter': 'planet', 'sun': 'star'}
print(d)
Output:
{'jupiter': 'planet', 'sun': 'star'}
Python OOPs Concepts
Object Oriented Programming is a fundamental
concept in Python, empowering developers to
build modular, maintainable, and scalable
applications
• Python Polymorphism
Polymorphism allows methods to have the
same name but behave differently based on the
object’s context. It can be achieved through
method overriding or overloading.
Types of Polymorphism
1.Compile-Time Polymorphism: This type of
polymorphism is determined during the
compilation of the program. It allows methods or
operators with the same name to behave
differently based on their input parameters or
usage. It is commonly referred to as method or
operator overloading.
2. Run-Time Polymorphism: This type of
polymorphism is determined during the
execution of the program. It occurs when a
subclass provides a specific implementation
for a method already defined in its parent
class, commonly known as method overriding.
• Python Encapsulation
• Encapsulation is the bundling of data
(attributes) and methods (functions) within a
class, restricting access to some components
to control interactions.
• A class is an example of encapsulation as it
encapsulates all the data that is member
functions, variables, etc.
• Data Abstraction
Abstraction hides the internal implementation details
while exposing only the necessary functionality. It
helps focus on “what to do” rather than “how to do it.”
• Types of Abstraction:
• Partial Abstraction: Abstract class contains both
abstract and concrete methods.
• Full Abstraction: Abstract class contains only abstract
methods (like interfaces).
Python Inheritance
• Inheritance allows a class (child class) to
acquire properties and methods of another
class (parent class). It supports hierarchical
classification and promotes code reuse.
Types of Inheritance
• Single Inheritance: A child class inherits from a single
parent class.
• Multiple Inheritance: A child class inherits from more
than one parent class.
• Multilevel Inheritance: A child class inherits from a
parent class, which in turn inherits from another class.
• Hierarchical Inheritance: Multiple child classes inherit
from a single parent class.
• Hybrid Inheritance: A combination of two or more types
of inheritance.

unit 1 Introduction to Python by N.KARTHIKEYAN

  • 1.
  • 2.
    • In Python,a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list.
  • 3.
    List can containduplicate items. • List in Python are alterable. Hence, we can modify, replace or delete the items. • List are ordered. It maintain the order of elements based on how they are added. • Accessing items in List can be done directly using their position (index), starting from 0.
  • 4.
    a = [10,20, 15] print(a[0]) # access first item a.append(11) # add item a.remove(20) # remove item print(a) Output 10 [10, 15, 11]
  • 5.
    Creating a List #List of integers a = [1, 2, 3, 4, 5] # List of strings b = ['apple', 'banana', 'cherry'] # Mixed data types c = [1, 'hello', 3.14, True] print(a) print(b) print(c)
  • 6.
    • Output • [1,2, 3, 4, 5] • ['apple', 'banana', 'cherry'] • [1, 'hello', 3.14, True]
  • 7.
    Adding Elements intoList • We can add elements to a list using the following methods: • append(): Adds an element at the end of the list. • extend(): Adds multiple elements to the end of the list. • insert(): Adds an element at a specific position.
  • 8.
    # Initialize anempty list a = [] # Adding 10 to end of list a.append(10) print("After append(10):", a) # Inserting 5 at index 0 a.insert(0, 5) print("After insert(0, 5):", a) # Adding multiple elements [15, 20, 25] at the end a.extend([15, 20, 25]) print("After extend([15, 20, 25]):", a)
  • 9.
    • After append(10):[10] • After insert(0, 5): [5, 10] • After extend([15, 20, 25]): [5, 10, 15, 20, 25]
  • 10.
    Python Arrays • InPython, array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together
  • 11.
    import array asarr # creating array of integers a = arr.array('i', [1, 2, 3]) # accessing First Araay print(a[0]) # Adding element to array a.append(5) print(a) Output 1 array('i', [1, 2, 3, 5])
  • 12.
    Create an Arrayin Python • Array in Python can be created by importing an array module. array( data_type , value_list ) is used to create array in Python with data type and value list specified in its arguments.
  • 13.
    import array asarr # creating array a = arr.array('i', [1, 2, 3]) # iterating and printing each item for i in range(0, 3): print(a[i], end=" ") Output 1 2 3
  • 14.
    Adding Elements toan Array • Elements can be added to the Python Array by using built-in insert() function. Insert is used to insert one or more data elements into an array.
  • 15.
    import array asarr # Integer array example a = arr.array('i', [1, 2, 3]) print("Integer Array before insertion:", *a) a.insert(1, 4) # Insert 4 at index 1 print("Integer Array after insertion:", *a) Output Integer Array before insertion: 1 2 3 Integer Array after insertion: 1 4 2 3
  • 16.
    Accessing Array Items importarray as arr a = arr.array('i', [1, 2, 3, 4, 5, 6]) print(a[0]) print(a[3]) b = arr.array('d', [2.5, 3.2, 3.3]) print(b[1]) print(b[2]) Output 1 4 3.2 3.3
  • 17.
    Removing Elements fromthe Array • Elements can be removed from the Python array by using built-in remove() function.
  • 18.
    import array arr =array.array('i', [1, 2, 3, 1, 5]) # using remove() method to remove first occurance of 1 arr.remove(1) print(arr) # pop() method - remove item at index 2 arr.pop(2) print(arr) Output array('i', [2, 3, 1, 5]) array('i', [2, 3, 5])
  • 19.
    Stack and Queuesin Python • Stack works on the principle of “Last-in, first- out”.
  • 20.
    # Python codeto demonstrate Implementing # stack using list stack = ["Amar", "Akbar", "Anthony"] stack.append("Ram") stack.append("Iqbal") print(stack) # Removes the last item print(stack.pop()) print(stack) # Removes the last item print(stack.pop()) print(stack)
  • 21.
    • Output:['Amar', 'Akbar','Anthony', 'Ram', 'Iqbal'] Iqbal • ['Amar', 'Akbar', 'Anthony', 'Ram'] Ram • ['Amar', 'Akbar', 'Anthony']
  • 22.
    Queue • works onthe principle of “First-in, first-out”.
  • 23.
    • # Pythoncode to demonstrate Implementing • # Queue using list • queue = ["Amar", "Akbar", "Anthony"] • queue.append("Ram") • queue.append("Iqbal") • print(queue) • # Removes the first item • print(queue.pop(0)) • print(queue) • # Removes the first item • print(queue.pop(0)) • print(queue)
  • 24.
    • Output:['Amar', 'Akbar','Anthony', 'Ram', 'Iqbal'] Amar • ['Akbar', 'Anthony', 'Ram', 'Iqbal'] Akbar • ['Anthony', 'Ram', 'Iqbal']
  • 25.
    Tuples in Python •Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable.
  • 26.
    # Note :In case of list, we use square # brackets []. Here we use round brackets () t = (10, 20, 30) print(t) print(type(t)) Output (10, 20, 30) <class 'tuple'>
  • 27.
    What is Immutablein Tuples? • Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python. • Like Lists, tuples are ordered and we can access their elements using their index values • We cannot update items to a tuple once it is created. • Tuples cannot be appended or extended. • We cannot remove items from a tuple once it is created.
  • 28.
    t = (1,2, 3, 4, 5) # tuples are indexed print(t[1]) print(t[4]) # tuples contain duplicate elements t = (1, 2, 3, 4, 2, 3) print(t) # updating an element t[1] = 100 print(t)
  • 29.
    2 5 (1, 2, 3,4, 2, 3) ERROR! Traceback (most recent call last): File "<main.py>", line 9, in <module> TypeError: 'tuple' object does not support item assignment === Code Exited With Errors ===
  • 30.
    Packing and Unpackinga Tuple • In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable.
  • 31.
    # Program tounderstand about # packing and unpacking in Python # this lines PACKS values # into variable a a = ("MNNIT Allahabad", 5000, "Engineering") # this lines UNPACKS values # of variable a (college, student, type_ofcollege) = a # print college name print(college) # print no of student print(student) # print type of college print(type_ofcollege)
  • 32.
    • Output: • MNNITAllahabad • 5000 • Engineering
  • 33.
    Sets • Set classis used to represent the collection of elements without duplicates, and without any inherent order to those elements. It is enclosed by the {} and each element is separated by the comma(,) and it is mutable.
  • 34.
    # set ofalphabet set = {'a', 'b', 'c', 'd', 'e'} print(set) Output: {'c', 'b', 'd', 'e', 'a'}
  • 35.
    Dictionaries • It isa mapping of different keys to its associated values. We use curly brackets { } to create dictionaries too.
  • 36.
    # Example ofDictionary d = {'jupiter': 'planet', 'sun': 'star'} print(d) Output: {'jupiter': 'planet', 'sun': 'star'}
  • 37.
    Python OOPs Concepts ObjectOriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications • Python Polymorphism Polymorphism allows methods to have the same name but behave differently based on the object’s context. It can be achieved through method overriding or overloading.
  • 38.
    Types of Polymorphism 1.Compile-TimePolymorphism: This type of polymorphism is determined during the compilation of the program. It allows methods or operators with the same name to behave differently based on their input parameters or usage. It is commonly referred to as method or operator overloading.
  • 39.
    2. Run-Time Polymorphism:This type of polymorphism is determined during the execution of the program. It occurs when a subclass provides a specific implementation for a method already defined in its parent class, commonly known as method overriding.
  • 40.
    • Python Encapsulation •Encapsulation is the bundling of data (attributes) and methods (functions) within a class, restricting access to some components to control interactions. • A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
  • 41.
    • Data Abstraction Abstractionhides the internal implementation details while exposing only the necessary functionality. It helps focus on “what to do” rather than “how to do it.” • Types of Abstraction: • Partial Abstraction: Abstract class contains both abstract and concrete methods. • Full Abstraction: Abstract class contains only abstract methods (like interfaces).
  • 42.
    Python Inheritance • Inheritanceallows a class (child class) to acquire properties and methods of another class (parent class). It supports hierarchical classification and promotes code reuse.
  • 43.
    Types of Inheritance •Single Inheritance: A child class inherits from a single parent class. • Multiple Inheritance: A child class inherits from more than one parent class. • Multilevel Inheritance: A child class inherits from a parent class, which in turn inherits from another class. • Hierarchical Inheritance: Multiple child classes inherit from a single parent class. • Hybrid Inheritance: A combination of two or more types of inheritance.