Python Programming Notes | Degree Level
PYTHON PROGRAMMING
Comprehensive Study Notes
Class & Objects | Lists | Tuples | Sequences | Sets | Dictionaries
Degree Level | For Notebook Use
UNIT 1: CLASS AND OBJECT
1.1 Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design
around data (objects) rather than functions and logic. Python is a fully object-oriented language.
Key Concepts of OOP
• Class: A blueprint or template for creating objects.
• Object: An instance of a class. It has attributes (data) and methods (functions).
• Encapsulation: Wrapping data and methods together inside a class.
• Inheritance: A class can inherit properties and methods from another class.
• Polymorphism: The ability to use a single interface for different data types.
• Abstraction: Hiding internal implementation details from the user.
1.2 Defining a Class in Python
A class is defined using the 'class' keyword followed by the class name and a colon.
Syntax:
class ClassName:
# Class body
def __init__(self, parameters):
[Link] = value
def method_name(self):
# method body
pass
Example 1: Simple Class Definition
class Student:
def __init__(self, name, age, roll_no):
[Link] = name # instance attribute
[Link] = age
Page 1 | Python Data Structures & OOP
Python Programming Notes | Degree Level
self.roll_no = roll_no
def display(self):
print('Name :', [Link])
print('Age :', [Link])
print('Roll No:', self.roll_no)
# Creating Objects (Instances)
s1 = Student('Alice', 20, 101)
s2 = Student('Bob', 22, 102)
# Calling method
[Link]()
[Link]()
Output:
Name : Alice
Age : 20
Roll No: 101
Name : Bob
Age : 22
Roll No: 102
1.3 The __init__() Method (Constructor)
The __init__() method is called automatically when an object is created. It initializes the object's
attributes. 'self' refers to the current instance of the class.
Note:
Every method in a class must have 'self' as the first parameter. 'self' is a reference to the current
object of the class.
1.4 Instance Variables vs Class Variables
Instance Variables
Instance variables are unique to each object. They are defined inside __init__() using self.
Class Variables
Class variables are shared across all instances of the class. They are defined directly inside the class
body.
class College:
college_name = 'ABC University' # Class variable (shared)
def __init__(self, student_name, branch):
self.student_name = student_name # Instance variable
[Link] = branch
Page 2 | Python Data Structures & OOP
Python Programming Notes | Degree Level
def show(self):
print('College :', College.college_name)
print('Student :', self.student_name)
print('Branch :', [Link])
c1 = College('Alice', 'Computer Science')
c2 = College('Bob', 'Electronics')
[Link]()
[Link]()
1.5 Methods in a Class
Types of Methods:
• Instance Method: Operates on instance (object) data. Uses 'self'.
• Class Method: Operates on class data. Uses @classmethod decorator and 'cls'.
• Static Method: Does not operate on instance or class data. Uses @staticmethod.
Example 2: All Three Method Types
class MathUtils:
pi = 3.14159 # class variable
def __init__(self, value):
[Link] = value
# Instance method
def square(self):
return [Link] ** 2
# Class method
@classmethod
def get_pi(cls):
return [Link]
# Static method
@staticmethod
def add(a, b):
return a + b
obj = MathUtils(5)
print([Link]()) # Output: 25
print(MathUtils.get_pi()) # Output: 3.14159
print([Link](3, 4)) # Output: 7
Page 3 | Python Data Structures & OOP
Python Programming Notes | Degree Level
1.6 Inheritance
Inheritance allows a child class to inherit attributes and methods from a parent class. This promotes
code reusability.
Types of Inheritance:
• Single Inheritance: One child class inherits from one parent class.
• Multiple Inheritance: One child class inherits from multiple parent classes.
• Multilevel Inheritance: A class inherits from a class which itself inherits from another class.
• Hierarchical Inheritance: Multiple child classes inherit from one parent class.
Example 3: Single Inheritance
class Animal: # Parent class
def __init__(self, name):
[Link] = name
def speak(self):
print([Link], 'makes a sound')
class Dog(Animal): # Child class
def speak(self): # Method overriding
print([Link], 'says: Woof!')
class Cat(Animal): # Child class
def speak(self):
print([Link], 'says: Meow!')
d = Dog('Tommy')
c = Cat('Whiskers')
[Link]() # Output: Tommy says: Woof!
[Link]() # Output: Whiskers says: Meow!
1.7 The super() Function
The super() function is used to call the parent class's method from the child class. It is commonly used
in __init__() to initialize parent class attributes.
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
class Employee(Person):
def __init__(self, name, age, emp_id):
super().__init__(name, age) # Calling parent constructor
self.emp_id = emp_id
def display(self):
Page 4 | Python Data Structures & OOP
Python Programming Notes | Degree Level
print(f'Name: {[Link]}, Age: {[Link]}, ID: {self.emp_id}')
e = Employee('Alice', 28, 'E001')
[Link]() # Output: Name: Alice, Age: 28, ID: E001
1.8 Encapsulation (Access Modifiers)
Encapsulation restricts direct access to class data. Python uses naming conventions:
Access Type Syntax Description
Public [Link] Accessible from anywhere
Protected self._name Should not be accessed outside class
(convention)
Private self.__name Cannot be accessed directly outside the
class
class BankAccount:
def __init__(self, owner, balance):
[Link] = owner # public
self._bank = 'SBI' # protected
self.__balance = balance # private
def get_balance(self): # getter method
return self.__balance
def deposit(self, amount):
self.__balance += amount
acc = BankAccount('Alice', 5000)
print([Link]) # Output: Alice
print(acc.get_balance()) # Output: 5000
[Link](2000)
print(acc.get_balance()) # Output: 7000
Page 5 | Python Data Structures & OOP
Python Programming Notes | Degree Level
UNIT 2: LIST
2.1 Introduction to List
A List is an ordered, mutable (changeable) collection of items. Lists can contain elements of different
data types including integers, floats, strings, and even other lists.
Key Properties:
Ordered | Mutable | Allows Duplicate Elements | Indexed (starts from 0) | Dynamic Size
Syntax:
list_name = [element1, element2, element3, ...]
Example:
fruits = ['apple', 'banana', 'cherry']
numbers = [10, 20, 30, 40, 50]
mixed = [1, 'Hello', 3.14, True]
empty = []
print(fruits) # ['apple', 'banana', 'cherry']
print(numbers) # [10, 20, 30, 40, 50]
2.2 Accessing List Elements
List elements are accessed using index. Python supports positive indexing (left to right) and negative
indexing (right to left).
colors = ['Red', 'Green', 'Blue', 'Yellow', 'Pink']
# Positive Indexing
print(colors[0]) # Red
print(colors[2]) # Blue
# Negative Indexing
print(colors[-1]) # Pink
print(colors[-2]) # Yellow
# Slicing: list[start : stop : step]
print(colors[1:4]) # ['Green', 'Blue', 'Yellow']
print(colors[:3]) # ['Red', 'Green', 'Blue']
print(colors[::2]) # ['Red', 'Blue', 'Pink']
2.3 List Operations and Methods
Method Description Example
Page 6 | Python Data Structures & OOP
Python Programming Notes | Degree Level
append(x) Adds x to the end [Link](5)
insert(i, x) Inserts x at index i [Link](2, 'Hi')
remove(x) Removes first x [Link](3)
pop(i) Removes & returns element at i [Link](1)
sort() Sorts list in ascending order [Link]()
reverse() Reverses the list [Link]()
len(lst) Returns length of list len(lst)
index(x) Returns index of x [Link]('apple')
count(x) Counts occurrences of x [Link](5)
extend(lst2) Adds elements of lst2 [Link]([6,7])
copy() Returns shallow copy lst2 = [Link]()
clear() Removes all elements [Link]()
Example: List Methods in Action
nums = [5, 2, 8, 1, 9, 3]
[Link](7) # [5, 2, 8, 1, 9, 3, 7]
[Link](2, 100) # [5, 2, 100, 8, 1, 9, 3, 7]
[Link](100) # [5, 2, 8, 1, 9, 3, 7]
[Link]() # [1, 2, 3, 5, 7, 8, 9]
[Link]() # [9, 8, 7, 5, 3, 2, 1]
print('Length:', len(nums)) # 7
print('Count of 5:', [Link](5)) # 1
print('Index of 8:', [Link](8)) # 1
2.4 List Comprehension
List Comprehension is a concise way to create a new list from an existing list or range. It is faster and
more Pythonic than a traditional loop.
Syntax:
new_list = [expression for item in iterable if condition]
Examples:
# Squares of numbers 1 to 10
squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Even numbers from a list
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [x for x in nums if x % 2 == 0]
Page 7 | Python Data Structures & OOP
Python Programming Notes | Degree Level
print(evens) # [2, 4, 6, 8, 10]
# Converting to uppercase
fruits = ['apple', 'banana', 'mango']
upper = [[Link]() for f in fruits]
print(upper) # ['APPLE', 'BANANA', 'MANGO']
Page 8 | Python Data Structures & OOP
Python Programming Notes | Degree Level
UNIT 3: TUPLE AND SEQUENCES
3.1 Introduction to Tuple
A Tuple is an ordered, immutable (unchangeable) collection of items. Once created, the elements of a
tuple cannot be modified, added, or deleted.
Key Properties:
Ordered | Immutable | Allows Duplicate Elements | Indexed | Faster than List | Hashable
Syntax:
tuple_name = (element1, element2, element3, ...)
Example:
coords = (10, 20) # Simple tuple
info = ('Alice', 22, 'BCA') # Mixed types
single = (5,) # Single element (note the comma!)
nested = ((1,2), (3,4), (5,6)) # Nested tuple
empty = () # Empty tuple
print(coords) # (10, 20)
print(info[0]) # Alice
print(info[-1]) # BCA
3.2 Why Use Tuples?
• Faster than lists for iteration.
• Used as dictionary keys (since they are hashable).
• Used to return multiple values from a function.
• Suitable for data that should not change (e.g., days of the week, RGB values).
3.3 Tuple Operations
Accessing Elements
t = (10, 20, 30, 40, 50)
print(t[0]) # 10
print(t[-1]) # 50
print(t[1:4]) # (20, 30, 40)
print(t[::-1]) # (50, 40, 30, 20, 10) - reverse
Tuple Methods
Method Description Example
count(x) Returns count of element x [Link](10)
Page 9 | Python Data Structures & OOP
Python Programming Notes | Degree Level
index(x) Returns index of first x [Link](30)
len(t) Returns total elements len(t)
max(t) Returns maximum value max(t)
min(t) Returns minimum value min(t)
sum(t) Returns sum of elements sum(t)
sorted(t) Returns sorted list (not tuple) sorted(t)
Example: Tuple Methods
marks = (85, 90, 78, 90, 92, 85, 90)
print('Count of 90:', [Link](90)) # 3
print('Index of 78:', [Link](78)) # 2
print('Max:', max(marks)) # 92
print('Min:', min(marks)) # 78
print('Sum:', sum(marks)) # 610
print('Sorted:', sorted(marks)) # [78, 85, 85, 90, 90, 90, 92]
3.4 Tuple Packing and Unpacking
# Packing - combining values into a tuple
person = 'Alice', 22, 'Engineer' # packing
print(person) # ('Alice', 22, 'Engineer')
# Unpacking - extracting values
name, age, job = person
print(name) # Alice
print(age) # 22
print(job) # Engineer
# Swap using tuples
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10
3.5 Sequences in Python
A Sequence is a collection of items arranged in a specific order. In Python, the following are sequence
types:
Sequence Type Mutable? Example Use Case
List Yes [1, 2, 3] General purpose collection
Tuple No (1, 2, 3) Fixed/read-only data
String No 'Hello' Text processing
Page 10 | Python Data Structures & OOP
Python Programming Notes | Degree Level
Range No range(1,10) Loop iteration
Common Sequence Operations
# All sequence types support these operations
s = [10, 20, 30, 40, 50]
# Indexing
print(s[0]) # 10
# Slicing
print(s[1:4]) # [20, 30, 40]
# Concatenation
s2 = s + [60, 70]
print(s2) # [10, 20, 30, 40, 50, 60, 70]
# Repetition
s3 = [1, 2] * 3
print(s3) # [1, 2, 1, 2, 1, 2]
# Membership
print(30 in s) # True
print(99 not in s) # True
# Length
print(len(s)) # 5
Page 11 | Python Data Structures & OOP
Python Programming Notes | Degree Level
UNIT 4: SET
4.1 Introduction to Set
A Set is an unordered, mutable collection of unique elements. Sets do not allow duplicate values. They
are mainly used for mathematical operations like union, intersection, and difference.
Key Properties:
Unordered | Mutable | No Duplicates | Not Indexed | Elements must be hashable (immutable)
Syntax:
set_name = {element1, element2, element3}
# OR
set_name = set([list_or_iterable])
Example:
fruits = {'apple', 'banana', 'cherry', 'apple'} # Duplicate removed
print(fruits) # {'banana', 'cherry', 'apple'} (unordered)
nums = set([1, 2, 3, 4, 4, 5]) # From list
print(nums) # {1, 2, 3, 4, 5}
empty = set() # Empty set (NOT {} which is a dict!)
4.2 Set Methods
Method Description Example
add(x) Adds element x to set [Link](10)
remove(x) Removes x (raises error if absent) [Link](5)
discard(x) Removes x (no error if absent) [Link](99)
pop() Removes & returns arbitrary element [Link]()
clear() Removes all elements [Link]()
copy() Returns a shallow copy s2 = [Link]()
len(s) Returns number of elements len(s)
in Membership test 5 in s
4.3 Set Operations (Mathematical)
Union ( | or union() )
Returns all elements from both sets (without duplicates).
Page 12 | Python Data Structures & OOP
Python Programming Notes | Degree Level
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # {1, 2, 3, 4, 5, 6}
print([Link](B)) # {1, 2, 3, 4, 5, 6}
Intersection ( & or intersection() )
Returns elements common to both sets.
print(A & B) # {3, 4}
print([Link](B)) # {3, 4}
Difference ( - or difference() )
Returns elements in A but not in B.
print(A - B) # {1, 2}
print([Link](B)) # {1, 2}
Symmetric Difference ( ^ or symmetric_difference() )
Returns elements in either A or B but not in both.
print(A ^ B) # {1, 2, 5, 6}
print(A.symmetric_difference(B)) # {1, 2, 5, 6}
4.4 Set Comparisons
X = {1, 2, 3}
Y = {1, 2, 3, 4, 5}
Z = {6, 7}
# Subset: is X a subset of Y?
print([Link](Y)) # True
print(X <= Y) # True
# Superset: is Y a superset of X?
print([Link](X)) # True
print(Y >= X) # True
# Disjoint: Do X and Z share no elements?
print([Link](Z)) # True
Practical Example: Remove Duplicates from a List
# Fastest way to remove duplicates
data = [1, 2, 2, 3, 4, 4, 4, 5]
unique = list(set(data))
print(unique) # [1, 2, 3, 4, 5]
Page 13 | Python Data Structures & OOP
Python Programming Notes | Degree Level
Page 14 | Python Data Structures & OOP
Python Programming Notes | Degree Level
UNIT 5: DICTIONARIES
5.1 Introduction to Dictionary
A Dictionary is an unordered, mutable collection of key-value pairs. Each key must be unique and
immutable (e.g., string, number, tuple). Values can be of any data type.
Key Properties:
Unordered (ordered from Python 3.7+) | Mutable | Keys must be unique & immutable | Values
can be any type | Key-Value mapping
Syntax:
dict_name = {key1: value1, key2: value2, key3: value3}
Example:
# Creating a dictionary
student = {
'name': 'Alice',
'age': 21,
'marks': 88.5,
'city': 'Delhi'
}
print(student) # {'name': 'Alice', 'age': 21, ...}
print(student['name']) # Alice
print(student['marks']) # 88.5
5.2 Accessing Dictionary Elements
info = {'brand': 'Toyota', 'model': 'Corolla', 'year': 2022}
# Method 1: Direct key access
print(info['brand']) # Toyota
# Method 2: get() - safe, returns None if key absent
print([Link]('model')) # Corolla
print([Link]('color')) # None (no error!)
print([Link]('color', 'White')) # White (default value)
5.3 Adding, Updating, Deleting Elements
d = {'a': 1, 'b': 2, 'c': 3}
# Adding new key-value
Page 15 | Python Data Structures & OOP
Python Programming Notes | Degree Level
d['d'] = 4
print(d) # {'a':1, 'b':2, 'c':3, 'd':4}
# Updating existing value
d['a'] = 100
print(d) # {'a':100, 'b':2, 'c':3, 'd':4}
# Deleting with del
del d['c']
print(d) # {'a':100, 'b':2, 'd':4}
# Deleting with pop() - returns deleted value
val = [Link]('b')
print(val) # 2
print(d) # {'a':100, 'd':4}
# popitem() removes last inserted item
[Link]()
print(d) # {'a':100}
5.4 Dictionary Methods
Method Description Example
keys() Returns all keys [Link]()
values() Returns all values [Link]()
items() Returns key-value pairs [Link]()
get(k, def) Returns value for k [Link]('name','N/A')
update(d2) Merges d2 into d [Link]({'x':9})
pop(k) Removes key k [Link]('age')
popitem() Removes last item [Link]()
clear() Empties dictionary [Link]()
copy() Returns shallow copy d2 = [Link]()
fromkeys() Creates dict from keys [Link](['a','b'],0)
5.5 Iterating Over a Dictionary
employee = {'name': 'Bob', 'dept': 'HR', 'salary': 50000}
# Iterating keys
for key in employee:
print(key)
# Iterating values
for val in [Link]():
Page 16 | Python Data Structures & OOP
Python Programming Notes | Degree Level
print(val)
# Iterating key-value pairs
for key, value in [Link]():
print(f'{key} => {value}')
# Output:
# name => Bob
# dept => HR
# salary => 50000
5.6 Dictionary Comprehension
Similar to List Comprehension, Dictionary Comprehension creates a new dictionary from an iterable in
a concise way.
Syntax:
new_dict = {key: value for item in iterable if condition}
Examples:
# Squares dictionary
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1:1, 2:4, 3:9, 4:16, 5:25}
# Filter students who passed (marks >= 50)
marks = {'Alice': 85, 'Bob': 42, 'Charlie': 67, 'Dave': 38}
passed = {name: m for name, m in [Link]() if m >= 50}
print(passed) # {'Alice': 85, 'Charlie': 67}
# Invert a dictionary (swap keys and values)
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in [Link]()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
5.7 Nested Dictionary
A dictionary that contains another dictionary as a value is called a nested dictionary. This is useful for
representing complex data structures.
# Nested Dictionary Example
students = {
'S001': {'name': 'Alice', 'age': 21, 'marks': 90},
'S002': {'name': 'Bob', 'age': 22, 'marks': 75},
'S003': {'name': 'Carol', 'age': 20, 'marks': 85}
}
# Accessing nested values
Page 17 | Python Data Structures & OOP
Python Programming Notes | Degree Level
print(students['S001']['name']) # Alice
print(students['S002']['marks']) # 75
# Iterating nested dictionary
for roll, info in [Link]():
print(f'Roll: {roll} | Name: {info["name"]} | Marks: {info["marks"]}')
Page 18 | Python Data Structures & OOP
Python Programming Notes | Degree Level
QUICK REFERENCE: Comparison of Data Structures
Feature List Tuple Set Dictionary String
Ordered Yes Yes No Yes (3.7+) Yes
Mutable Yes No Yes Yes No
Duplicates Yes Yes No Keys: No Yes
Indexed Yes Yes No By Key Yes
Syntax [] () {} { k:v } ''
Speed Medium Fast Fast Fast Fast
IMPORTANT EXAM QUESTIONS
1. Define a class in Python. What is the difference between a class and an object? Give an
example.
2. Explain the concept of inheritance in Python with a suitable example.
3. What is the difference between a list and a tuple? When should you use each?
4. Explain list comprehension with examples.
5. What are sets in Python? Explain union, intersection, and difference with examples.
6. Explain dictionary methods: keys(), values(), items(), get(). Give examples.
7. Write a Python program to implement a Student class with attributes and methods.
8. Explain the difference between remove() and discard() in sets.
9. What is dictionary comprehension? Give examples.
10. Explain tuple packing and unpacking with examples.
Study Tips:
1. Always practice code by typing it, not just reading. 2. Try modifying examples to test your
understanding. 3. Focus on the difference between mutable and immutable types. 4.
Remember: Lists=[], Tuples=(), Sets={}, Dicts={k:v}
--- END OF NOTES ---
Page 19 | Python Data Structures & OOP