PYTHON FOR MACHINE
LEARNING (23CSH-281)
Unit 2 : String, List and dictionaries, tuples and sets
Unit 2 Syllabus ::
Compiled by : Subhayu
Chapter 1 : Strings
1. Introduction to Strings in Python
A string is a sequence of characters enclosed within single ('), double ("), or triple
('' or """) quotes in Python.
Strings are immutable, meaning they cannot be changed once c reated.
Example:
s1 = 'Hello'
s2 = "World"
s3 = '''Python Strings'''
2. str Class in Python
In Python, strings belong to the built-in str class. The str class provides various
methods for string manipulation.
Example:
print(type("Hello")) # Output: <class 'str'>
3. Inbuilt Functions for Strings
Function Description Example
len(s) Retur ns the length of the len("Python") → 6
string
s.lower() Con verts string to lowercase "PYTHON".lower() → python
s.upper() Con verts string to uppercase "python".upper() → PYTHON
s.strip() Removes leading and " hello ".strip() → "hello"
trailing spaces
s.replace(a, b) Replaces a with b in string "hello".replace("l", "z") → "hezzo"
s.count(x) Counts occur rences of x in "banana".count("a") → 3
string
s.find(x) Finds first occur rence index "hello".find("l") → 2
of x
4. Indexing and Slicing Strings
● Indexing: Accessing indi vidual characters using positive (left to right) or
negative (right to left) indices.
● Slicing: Extracting a part of a string using the for mat s[start:end:step].
Example:
s = "Python"
print(s[0]) # Output: P
print(s[-1]) # Output: n
print(s[1:4]) # Output: yth
print(s[::-1]) # Output: nohtyP (Re versing a string)
5. Traversing a String
Tra versing means accessing each character in a string one by one. This can be
done using a for loop.
Example:
s = "Python"
for char in s:
print(char, end=" ")
# Output: P y t h o n
6. String Operators
Operator Usage Example
+ Concatenation "Hello" + "World" →
"HelloWorld"
* Repetition "Hi" * 3 → "HiHiHi"
in Membership Check "a" in "apple" → True
not in Non-membership "x" not in "apple" → True
Check
7. String Operations
Python provides se veral methods to manipulate strings.
Splitting and Joining Strings
● split(separator): Splits a string into a list based on the separator.
● join(iterable): Joins elements of an iterable (list, tuple) into a string.
Example:
s = "Python is fun"
words = s.split() # Default separator is space
print(words) # Output: ['Python', 'is', 'fun']
ne w_s = "-".join(words)
print(ne w_s) # Output: Python-is-fun
Checking String Properties
● s.isalpha(): Retur ns True if all characters are alphabets.
● s.isdigit(): Retur ns True if all characters are digits.
● s.isspace(): Retur ns True if all characters are whitespace.
Example:
print("Hello".isalpha()) # Output: True
print("1234".isdigit()) # Output: True
print(" ".isspace()) # Output: True
8. NumPy Arrays (1D, 2D, Matrices, and
Operations)
While strings are useful for text processing, numerical computations require
NumPy arrays.
1D Array
A 1D array is similar to a list but optimized for numerical operations.
Example:
import numpy as np
ar r = np.ar ray([1, 2, 3, 4, 5])
print(ar r) # Output: [1 2 3 4 5]
2D Array
A 2D array is a matri x with rows and columns.
Example:
ar r2D = np.ar ray([[1, 2, 3], [4, 5, 6]])
print(ar r2D)
# Output:
# [[1 2 3]
# [4 5 6]]
Matrix Operations
NumPy supports various matri x operations like addition, multiplication, and
transposition.
Example:
A = np.ar ray([[1, 2], [3, 4]])
B = np.ar ray([[5, 6], [7, 8]])
print(A + B) # Matri x Addition
print(A * B) # Element-wise Multiplication
print(np.dot(A, B)) # Matri x Multiplication
Summary of Key Takeaways
● Strings are immutable sequences of characters.
● Indexing and slicing allow selecti ve access to characters.
● String operators like +, *, and in help in string manipulation.
● Inbuilt string methods like upper(), replace(), and split() provide powerful
functionalities.
● NumPy arrays offer efficient handling of numerical data, including 1D,
2D arrays, and matrices.
Theory Questions & Answers on
Strings
1. What are strings in Python? How are they different from lists?
Answer: A string is a sequence of characters enclosed in quotes (' ', " ", ''' ''', """ """).
Strings are immutable, meaning they cannot be changed after c reation. In
contrast, lists are mutable, allowing elements to be modified.
2. What are the different ways to create a string in Python?
Answer:
A string can be c reated in three ways:
s1 = 'Single quotes'
s2 = "Double quotes"
s3 = '''Triple quotes allow multiple lines'''
Triple quotes (''' or """) are used for multi-line strings or docstrings.
3. What does it mean that strings in Python are immutable?
Answer:
Once a string is c reated, its content cannot be changed. Any operation that
modifies a string actually c reates a new string instead of modifying the original
one.
Example:
s = "Hello"
s = s + " World" # A ne w string is c reated
print(s) # Output: Hello World
4. What is string slicing? How is it used?
Answer:
String slicing allows extracting a part of the string using
string[start:end:step].
Example:
s = "Python"
print(s[1:4]) # Output: yth
print(s[:3]) # Output: Pyt
print(s[::-1]) # Output: nohtyP (Re versed string)
5. What are some common string operations in Python?
Answer:
Operation Example Output
Concatenation "Hello" + "World" "HelloWorld"
(+)
Repetition (*) "Hi" * 3 "HiHiHi"
Membership "a" in "apple" True
(in)
Slicing "Python"[1:4] "yth"
Length (len()) len("Python") 6
6. What are escape characters in Python? Name a few.
Answer:
Escape characters allow including special characters in a string. They begin
with a backslash (\).
Escape Meaning
Sequence
\n Ne w line
\t Tab space
\' Single
quote
\" Double
quote
\\ Backslash
Example:
python
CopyEdit
print("Hello\nWorld") # Output: Hello (ne wline) World
7. How do you check if a string contains only letters, digits, or
spaces?
Answer:
Method Usage Example Outpu
t
isalpha() All characters are "Hello".isalpha() True
alphabets
isdigit() All characters are "1234".isdigit() True
digits
isspace() All characters are " ".isspace() True
spaces
Coding Questions & Solutions on
Strings
1. Write a program to count the number of vowels in a string.
def count_vowels(s):
vowels = "aeiouAEIOU"
count = sum(1 for char in s if char in vowels)
retur n count
# Example
print(count_vowels("Hello World")) # Output: 3
2. Write a program to reverse a string without using slicing ([::-1]).
def re verse_string(s):
re versed_s = ""
for char in s:
re versed_s = char + re versed_s
retur n re versed_s
# Example
print(re verse_string("Python")) # Output: nohtyP
3. Write a program to check if a string is a palindrome.
def is_palindrome(s):
retur n s == s[::-1]
# Example
print(is_palindrome("madam")) # Output: True
print(is_palindrome("hello")) # Output: False
4. Write a program to remove all spaces from a string.
def remove_spaces(s):
retur n s.replace(" ", "")
# Example
print(remove_spaces("Hello World")) # Output: HelloWorld
5. Write a program to find the most frequent character in a string.
from collections import Counter
def most_frequent_char(s):
freq = Counter(s)
retur n ma x(freq, key=freq.get)
# Example
print(most_frequent_char("banana")) # Output: a
6. Write a program to count the occurrence of each word in a
sentence.
def word_count(sentence):
words = sentence.split()
word_freq = {word: words.count(word) for word in set(words)}
retur n word_freq
# Example
print(word_count("apple banana apple orange banana apple"))
# Output: {'banana': 2, 'orange': 1, 'apple': 3}
7. Write a program to capitalize the first letter of each word in a
string.
def capitalize_words(s):
retur n s.title()
# Example
print(capitalize_words("hello world! python is fun."))
# Output: Hello World! Python Is Fun.
Chapter 2: Lists and Dictionaries in
Python
1. Lists in Python
A list is a mutable, ordered collection of elements in Python. It can store values
of different data types (integers, strings, floats, or e ven other lists).
1.1 Creating a List
Lists are defined using square brackets [].
# Creating a list
numbers = [10, 20, 30, 40, 50]
mi xed_list = [1, "Hello", 3.14, True]
print(numbers) # Output: [10, 20, 30, 40, 50]
print(mi xed_list) # Output: [1, 'Hello', 3.14, True]
1.2 Accessing Elements in a List
Elements in a list can be accessed using indexing (list[index]).
fruits = ["apple", "banana", "cher ry", "date"]
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: date (Negati ve indexing: last element)
1.3 List Slicing
Slicing allows extracting a subset of the list using [start:end:step].
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30] (First three elements)
print(numbers[::2]) # Output: [10, 30, 50] (Every second element)
print(numbers[::-1]) # Output: [60, 50, 40, 30, 20, 10] (Re verse list)
1.4 List Operators
Operator Description Example Output
+ Concatenation [1,2] + [3,4] [1,2,3,4]
* Repetition [1,2] * 3 [1,2,1,2,1,2]
in Membership 3 in [1,2,3] True
Check
len() Length len([1,2,3]) 3
1.5 List Methods
Method Usage Example Output
append() Adds element at end lst.append(10) [1,2,3,10]
insert() Adds at specific index lst.insert(1, 5) [1,5,2,3]
remove() Removes first lst.remove(2) [1,3]
occur rence
pop() Removes element by lst.pop(1) [1,3]
index
sort() Sorts list lst.sort() [1,2,3]
re verse() Re verses list lst.re verse() [3,2,1]
1.6 Splitting and Joining Lists
Splitting: Con vert a string into a list using split().
sentence = "Python is fun"
words = sentence.split() # Default separator is space
print(words) # Output: ['Python', 'is', 'fun']
Joining: Con vert a list into a string using join().
words = ['Python', 'is', 'a wesome']
sentence = " ".join(words)
print(sentence) # Output: Python is a wesome
2. Dictionaries in Python
A dictionary is an unordered collection of key-value pairs. Unlike lists,
dictionaries are accessed using keys instead of index numbers.
2.1 Creating a Dictionary
Dictionaries are defined using curly braces {}.
# Creating a dictionary
student = {
"name": "John",
"age": 21,
"marks": 85
print(student) # Output: {'name': 'John', 'age': 21, 'marks': 85}
2.2 Accessing Values in a Dictionary
Values can be accessed using keys.
print(student["name"]) # Output: John
print(student.get("age")) # Output: 21
2.3 Adding and Updating Values
student["city"] = "Ne w York" # Adding a ne w key-value pair
student["age"] = 22 # Updating an existing key
print(student)
# Output: {'name': 'John', 'age': 22, 'marks': 85, 'city': 'Ne w York'}
2.4 Deleting Items in a Dictionary
del student["marks"] # Deleting a specific key
print(student) # Output: {'name': 'John', 'age': 22, 'city': 'Ne w York'}
student.clear() # Clears all items
print(student) # Output: {}
2.5 Traversing a Dictionary
Using for loop to iterate over keys and values:
for key, value in student.items():
print(key, ":", value)
Output:
name : John
age : 22
city : Ne w York
2.6 Dictionary Methods
Metho Usage Example Output
d
keys() Retur ns all student.keys() dict_keys(['name', 'age', 'city'])
keys
values( Retur ns all student.values() dict_values(['John', 22, 'Ne w
) values York'])
items() Retur ns student.items() dict_items([('name', 'John'),
key-value ('age', 22), ('city', 'Ne w York')])
pairs
update Merges student.update({'marks {'name': 'John', 'age': 22, 'city':
() dictionaries ': 90}) 'Ne w York', 'marks': 90}
Example to Remember Lists vs. Dictionaries
Think of a list as a train where each compartment is an indexed seat (position
matters).
Think of a dictionary as a phone book where you search by name (key) instead
of index.
Summary of Key Concepts
✅ Lists
● Ordered collection (Index-based access)
● Mutable (Can be changed)
● Supports multiple data types
● Common methods: append(), pop(), sort(), re verse()
✅ Dictionaries
● Unordered collection (Key-based access)
● Mutable but keys must be unique
● Optimized for fast lookups
● Common methods: get(), keys(), values(), update()
Theory Questions with Answers (Lists &
Dictionaries)
Q1. What is a list in Python, and how does it differ from an array?
Answer:
A list in Python is a mutable, ordered collection that can store elements of
different data types (integers, floats, strings, etc.). Unlike ar rays in other
programming languages, Python lists do not require all elements to be of the
same data type. Lists support dynamic memory allocation, whereas ar rays (in
libraries like NumPy) are more memory-efficient for large datasets of the same
type.
Q2. What are some key operations that can be performed on lists?
Answer:
Some common list operations include:
● Indexing: Accessing elements using list[index]
● Slicing: Extracting a portion using [start:end:step]
● Appending & Inserting: Adding elements (append(), insert())
● Sorting & Reversing: sort(), re verse()
● Removing Elements: remove(), pop(), del
● Concatenation: list1 + list2
● Membership Test: element in list
Q3. How do dictionaries work in Python?
Answer:
A dictionary is an unordered collection of key-value pairs. Each key is unique
and is used to access the cor responding value. Unlike lists, dictionaries provide
fast lookups since they use hashing inter nally.
Example:
student = {"name": "John", "age": 21, "marks": 90}
print(student["name"]) # Output: John
Q4. How do you iterate through a dictionary?
Answer:
Dictionaries can be tra versed using loops:
student = {"name": "John", "age": 21, "marks": 90}
for key in student:
print(key, ":", student[key])
# OR using items() for both keys and values
for key, value in student.items():
print(key, "->", value)
Q5. Explain the difference between get() and direct dictionary
access (dict[key]).
Answer:
● Using dict[key]: Raises a KeyError if the key does not exist.
● Using dict.get(key, default_value): Retur ns None or a default value if the
key is missing, a voiding er rors.
Example:
student = {"name": "Alice"}
print(student.get("age", "Not Found")) # Output: Not Found
Q6. How do you remove items from a dictionary?
Answer:
Methods to remove dictionary elements:
● del dict[key] → Removes a specific key-value pair
● dict.pop(key) → Removes and retur ns the value
● dict.clear() → Clears the entire dictionary
Example:
student = {"name": "Alice", "age": 20}
del student["age"]
print(student) # Output: {'name': 'Alice'}
Q7. Why should dictionary keys be immutable?
Answer:
Dictionaries use hashing to store keys efficiently. Since mutable objects (like
lists) can change, their hash values can also change, leading to inconsistency
in key lookups. Therefore, only immutable types (like strings, numbers, and
tuples) are allowed as dictionary keys.
Example (in valid key):
my_dict = {[1, 2, 3]: "List Key"} # ❌ TypeEr ror: unhashable type: 'list'
Coding-Based Questions with Solutions
Q1. Write a Python program to remove duplicates from a list.
Solution:
def remove_duplicates(lst):
retur n list(set(lst))
numbers = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicates(numbers)) # Output: [1, 2, 3, 4, 5]
Q2. Write a program to find the second largest number in a list.
Solution:
def second_largest(lst):
unique_numbers = list(set(lst)) # Remove duplicates
unique_numbers.sort(re verse=True) # Sort in descending order
retur n unique_numbers[1] # Second largest element
numbers = [10, 20, 4, 45, 99, 99, 45]
print(second_largest(numbers)) # Output: 45
Q3. Write a program to merge two dictionaries.
Solution:
dict1 = {"a": 10, "b": 20}
dict2 = {"c": 30, "d": 40}
merged_dict = {**dict1, **dict2} # Merging dictionaries
print(merged_dict) # Output: {'a': 10, 'b': 20, 'c': 30, 'd': 40}
(Alter nati ve method: dict1.update(dict2))
Q4. Write a Python program to count occurrences of each word in
a string using a dictionary.
Solution:
def word_count(sentence):
words = sentence.split()
count_dict = {}
for word in words:
count_dict[word] = count_dict.get(word, 0) + 1 # Inc rement count
retur n count_dict
text = "apple banana apple orange banana apple"
print(word_count(text))
# Output: {'apple': 3, 'banana': 2, 'orange': 1}
Q5. Write a program to find the intersection of two lists.
Solution:
def list_intersection(lst1, lst2):
retur n list(set(lst1) & set(lst2)) # Set intersection operator
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
print(list_intersection(list1, list2)) # Output: [3, 4, 5]
Q6. Write a Python program to reverse a dictionary (swap keys
and values).
Solution:
def re verse_dict(d):
retur n {v: k for k, v in d.items()} # Dictionary comprehension
original = {"a": 1, "b": 2, "c": 3}
print(re verse_dict(original)) # Output: {1: 'a', 2: 'b', 3: 'c'}
Q7. Write a Python program to sort a list of dictionaries based on a
key.
Solution:
students = [
{"name": "Alice", "marks": 85},
{"name": "Bob", "marks": 72},
{"name": "Charlie", "marks": 90}
sorted_students = sorted(students, key=lambda x: x["marks"], re verse=True)
print(sorted_students)
Output:
[
{'name': 'Charlie', 'marks': 90},
{'name': 'Alice', 'marks': 85},
{'name': 'Bob', 'marks': 72}
]
Chapter 3: Tuples and Sets
1. Tuples in Python
1.1 What is a Tuple?
A tuple is an immutable, ordered collection of elements in Python. Unlike lists,
once c reated, tuples cannot be modified (no insertion, deletion, or updating of
elements). Tuples allow duplicate values and can store elements of different data
types.
1.2 Creating Tuples
Tuples can be c reated using parentheses () or the tuple() function.
python
CopyEdit
# Creating tuples
t1 = (1, 2, 3) # Tuple with integers
t2 = ("apple", "banana", "cher ry") # Tuple with strings
t3 = (10, "Python", 3.14) # Mi xed data types
t4 = tuple([1, 2, 3]) # Using tuple() constructor
Special Cases
Single-element tuples must include a comma:
t = (5,) # Cor rect
t = (5) # Incor rect (c reates an integer, not a tuple)
● Empty tuple: empty_tup = ()
1.3 Accessing Tuple Elements
Tuples support indexing and slicing, just like lists.
t = (10, 20, 30, 40, 50)
print(t[0]) # 10 (First element)
print(t[-1]) # 50 (Last element)
print(t[1:4]) # (20, 30, 40) (Slicing)
1.4 Tuple Operations
Operation Syntax Example Output
Concatenati t1 + t2 (1, 2) + (3, 4) (1, 2, 3, 4)
on
Repetition t*n ('A',) * 3 ('A', 'A', 'A')
Membershi x in t 3 in (1, 2, 3) True
Length len(t) len((5,6,7)) 3
Count t.count(x) (1, 2, 2).count(2) 2
Index t.index(x) (10, 20, 1
30).index(20)
1.5 Tuple Packing and Unpacking
Packing: Storing multiple values into a tuple.
Unpacking: Extracting tuple elements into variables.
# Packing
data = ("Alice", 25, "Engineer")
# Unpacking
name, age, profession = data
print(name) # Alice
print(age) # 25
2. Sets in Python
2.1 What is a Set?
A set is an unordered, mutable collection of unique elements. It does not allow
duplicates and is commonly used for mathematical set operations like union,
intersection, and difference.
2.2 Creating Sets
s1 = {1, 2, 3, 4} # Using curly braces
s2 = set([1, 2, 3]) # Using set() function
s3 = set() # Empty set (NOT `s3 = {}` because that c reates an empty
dictionary)
2.3 Set Operations
Operation Syntax Example Output
Union `A B` `{1,2}
Intersection A&B {1,2} & {2}
{2,3}
Difference A-B {1,2,3} - {1}
{2,3}
Symmetric A^B {1,2} ^ {2,3} {1,3}
Diff
Membership x in S 3 in {1,2,3} True
Length len(S) len({1,2,3}) 3
2.4 Set Methods
Method Usage Example Output
add(x) Adds an element S.add(5) {1,2,3,5}
remove(x) Removes element, er rors if S.remove(2) {1,3}
missing
discard(x Removes element, no er ror if S.discard(1 {1,3}
) missing 0)
pop() Removes and retur ns a random S.pop() Varies
element
clear() Removes all elements S.clear() {}
2.5 Frozen Sets (Immutable Sets)
A frozenset is an immutable set, meaning no modifications (add/remove).
fs = frozenset([1, 2, 3, 4])
# fs.add(5) ❌ Er ror: Cannot modify frozensets
Example: Tuples and Sets in Real Life
Imagine a restaurant menu:
● The menu (tuple) is fi xed (immutable). Example: menu = ("Pizza",
"Burger", "Pasta")
● The customers who have visited (set) keeps changing, and no duplicates
are allowed. Example: customers = {"Alice", "Bob", "Charlie"}
Theory Questions & Answers on
Tuples and Sets
1. What is a tuple? How is it different from a list?
Answer:
A tuple is anordered, immutable collection of elements in Python, defined
using parentheses (). Unlike lists, tuples cannot be modified once c reated (no
addition, removal, or modification of elements). Lists, on the other hand, are
mutable.
2. How do you create a tuple with a single element? Why is a
comma necessary?
Answer:
A single-element tuple must ha ve a trailing comma to differentiate it from a
regular value.
t = (5,) # Cor rect
t = (5) # Incor rect (This is an integer)
Without the comma, Python treats t = (5) as an integer rather than a tuple.
3. How do you access elements of a tuple? Explain with an
example.
Answer:
Elements of a tuple can be accessed using indexing and slicing:
t = (10, 20, 30, 40, 50)
print(t[0]) # 10 (First element)
print(t[-1]) # 50 (Last element)
print(t[1:4]) # (20, 30, 40) (Slicing)
4. What are set operations? Name and explain three important set
operations.
Answer:
Set operations allow mathematical manipulations on sets. Three important
ones are:
Union (|) - Combines t wo sets, removing duplicates.
python
CopyEdit
{1, 2} | {2, 3} # Output: {1, 2, 3}
1.
Intersection (&) - Retur ns common elements bet ween t wo sets.
python
CopyEdit
{1, 2} & {2, 3} # Output: {2}
2.
Difference (-) - Retur ns elements in one set but not in the other.
{1, 2, 3} - {2, 3} # Output: {1}
5. What is the difference between remove() and discard() in sets?
Answer:
● remove(x): Removes element x from a set; raises an error if x is missing.
● discard(x): Removes element x but does not raise an error if x is missing.
s = {1, 2, 3}
s.remove(2) # {1, 3}
s.discard(10) # No er ror, set remains {1, 3}
6. What is a frozenset? How is it different from a normal set?
Answer:
A frozenset is an immutable set, meaning it cannot be modified after c reation.
It is useful when a set needs to be used as a dictionary key or added to another
set.
fs = frozenset([1, 2, 3])
# fs.add(4) ❌ Er ror: Frozensets are immutable
7. How do you iterate over a set and a tuple?
Answer:
Both sets and tuples can be iterated using a for loop:
# Iterating over a tuple
t = (10, 20, 30)
for item in t:
print(item)
# Iterating over a set
s = {100, 200, 300}
for item in s:
print(item)
Coding Questions & Solutions on
Tuples and Sets
1. Write a Python program to find the length of a tuple.
Solution:
t = (10, 20, 30, 40, 50)
print("Length of tuple:", len(t))
Output:
Length of tuple: 5
2. Write a program to check if an element exists in a tuple.
Solution:
t = (1, 2, 3, 4, 5)
x=3
if x in t:
print(f"{x} is in the tuple")
else:
print(f"{x} is not in the tuple")
Output:
3 is in the tuple
3. Convert a tuple to a list and vice versa.
Solution:
t = (10, 20, 30)
lst = list(t) # Tuple to list
print("List:", lst)
lst2 = [1, 2, 3]
t2 = tuple(lst2) # List to tuple
print("Tuple:", t2)
Output:
List: [10, 20, 30]
Tuple: (1, 2, 3)
4. Write a program to remove duplicates from a list using sets.
Solution:
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(set(lst))
print("List without duplicates:", unique_lst)
Output:
List without duplicates: [1, 2, 3, 4, 5]
5. Find the intersection of two sets.
Solution:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
common_elements = set1 & set2
print("Intersection:", common_elements)
Output:
Intersection: {3, 4}
6. Write a program to add elements to a set and remove elements
from it.
Solution:
s = {10, 20, 30}
s.add(40) # Adding element
s.remove(20) # Removing element
print("Updated set:", s)
Output:
Updated set: {10, 30, 40}
7. Write a Python program to count the occurrences of each
element in a tuple.
Solution:
t = (1, 2, 3, 2, 1, 4, 2, 5)
count_dict = {}
for item in t:
count_dict[item] = count_dict.get(item, 0) + 1
print("Element frequencies:", count_dict)
Output:
Element frequencies: {1: 2, 2: 3, 3: 1, 4: 1, 5: 1}
Chapter 4 : Object-Oriented
Programming (OOP) in Python
Object-Oriented Programming (OOP) is a programming paradigm that
organizes data and beha vior into objects and classes rather than functions
and logic alone. Python, being an object-oriented language, provides powerful
OOP features that help in building scalable and modular applications.
1. Basics of Object-Oriented Programming
Object-Oriented Programming (OOP) is centered around the concept of
objects, which encapsulate data (attributes) and methods (functions that operate
on the data).
Key Concepts of OOP
1. Class → A blueprint for c reating objects.
2. Object → An instance of a class.
3. Method → A function inside a class that operates on objects.
4. Attribute → Variables inside a class that store object data.
Example: Defining a Class and Creating Objects
class Car:
def __init__(self, brand, model, year): # Constructor
self.brand = brand
self.model = model
self.year = year
def display_info(self): # Method
print(f"{self.year} {self.brand} {self.model}")
# Creating objects
car1 = Car("Tesla", "Model S", 2022)
car2 = Car("Toyota", "Corolla", 2020)
# Calling method
car1.display_info()
car2.display_info()
Output:
2022 Tesla Model S
2020 Toyota Corolla
2. Classes and Objects
Defining a Class
A class is a user-defined template that desc ribes the beha vior and properties of
an object.
class Student:
pass # Empty class
Creating an Object
Objects are instances of a class.
s1 = Student()
s2 = Student()
3. Constructor (__init__())
A constructor is a special method that initializes object attributes when an
object is c reated. It is defined using __init__().
class Student:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age
s1 = Student("Alice", 21)
print(s1.name, s1.age)
Output:
Alice 21
4. Methods in Classes
Types of Methods
1. Instance Method → Operates on instance variables.
2. Class Method (@classmethod) → Operates on class-le vel attributes.
3. Static Method (@staticmethod) → Does not modify class or instance
attributes.
class School:
school_name = "Green wood High" # Class variable
def __init__(self, student_name):
self.student_name = student_name # Instance variable
def show(self): # Instance method
print(f"Student: {self.student_name} | School: {School.school_name}")
@classmethod
def change_school(cls, ne w_name): # Class method
cls.school_name = ne w_name
@static method
def school_motto():
print("Education is the key to success!")
# Using methods
s1 = School("John")
s1.show()
School.change_school("Bright Future School")
s1.show()
School.school_motto()
Output:
Student: John | School: Green wood High
Student: John | School: Bright Future School
Education is the key to success!
5. Encapsulation
Encapsulation is hiding the internal data of an object to pre vent direct
modification. It is done using private variables (prefi xing an attribute with __).
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Pri vate variable
def deposit(self, amount):
self.__balance += amount
print("Deposit successful!")
def get_balance(self):
retur n self.__balance
acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance()) # ✅ Cor rect way
Output:
Deposit successful!
1500
Direct access (acc.__balance) will result in an AttributeError.
6. Inheritance
Inheritance allows one class to acquire the properties and methods of another
class.
Types of Inheritance
1. Single Inheritance → One class inherits from another.
2. Multiple Inheritance → A class inherits from multiple classes.
3. Multilevel Inheritance → A class inherits from another class, which itself
is inherited from another class.
Example: Single Inheritance
class Animal:
def sound(self):
print("Animals make sounds.")
class Dog(Animal): # Dog inherits from Animal
def sound(self):
print("Dog barks.")
d = Dog()
d.sound()
Output:
Dog barks.
7. Method Overriding and super()
When a child class redefines a method of its parent class, it is called method
overriding. The super() function calls the parent class’s method.
class Parent:
def show(self):
print("This is the parent class.")
class Child(Parent):
def show(self):
super().show() # Calls parent method
print("This is the child class.")
c = Child()
c.show()
Output:
This is the parent class.
This is the child class.
8. Operator Overloading
Python allows operator overloading, enabling us to define how an operator
beha ves for user-defined objects.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
retur n Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2 # Uses __add__ method
print(p3.x, p3.y)
Output:
46
9. Polymorphism
Polymorphism allows methods in different classes to ha ve the same name but
perfor m different tasks.
class Bird:
def fly(self):
print("Birds can fly.")
class Penguin(Bird):
def fly(self):
print("Penguins cannot fly.")
for obj in [Bird(), Penguin()]:
obj.fly()
Output:
Birds can fly.
Penguins cannot fly.
10. Summary of OOP Concepts
Feature Description
Class Blueprint for c reating objects.
Object Instance of a class.
Constructor Initializes object attributes.
Encapsulation Hiding pri vate data.
Inheritance Child class acquiring parent properties.
Polymorphism Different classes using the same method name
differently.
Method Overriding Redefining a parent class method in a child
class.
Operator Redefining operators for custom objects.
Overloading
Real-Life Example of OOP
Think of a Car Manufacturing Company:
● Class: Blueprint of a car.
● Object: A specific car model (e.g., Tesla Model 3).
● Encapsulation: Engine details are pri vate, users only access through car
functions.
● Inheritance: "ElectricCar" inherits from "Car".
● Polymorphism: Different car brands use different "start" mechanisms.
● Operator Overloading: Comparing t wo cars by price using >.
Theory Questions & Answers
1. What is Object-Oriented Programming (OOP)?
Answer:
Object-Oriented Programming (OOP) is a programming paradigm that
organizes data and beha vior into objects. It allows for better modularity, code
reusability, and scalability by structuring programs around real-world entities.
The main OOP principles are Encapsulation, Inheritance, Polymorphism, and
Abstraction.
2. What is the difference between a Class and an Object?
Answer:
Feature Class Object
Definition A blueprint for c reating objects An instance of a class
Memory Doesn't consume memory directly Occupies memory
Example Car class defines properties like Car1 = Car("Tesla",
brand, model, and speed "Model S")
3. Explain Encapsulation with an example.
Answer:
Encapsulation is the concept ofhiding internal details of an object and
exposing only necessary functionalities. It is achie ved by using private variables
(__variable_name) and providing access through methods.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Pri vate variable
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
retur n self.__balance # Controlled access
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # ✅ Works
print(account.__balance) # ❌ Er ror (pri vate variable)
4. What are instance, class, and static methods?
Answer:
Method Type Definition Uses Uses
self? cls?
Instance
Method
Works with instance attributes ✅ Yes ❌ No
Class
Method
Works with class attributes ❌ No ✅ Yes
Static
Method
Independent method, doesn't modify class ❌ No ❌ No
or instance attributes
Example:
class Example:
value = 10
def instance_method(self):
print("Instance method:", self.value)
@classmethod
def class_method(cls):
print("Class method:", cls.value)
@static method
def static_method():
print("Static method: No instance/class variables used")
5. What is Inheritance? Name its types.
Answer:
Inheritance allows a class to acquire properties and methods from another
class, promoting code reuse.
Types of Inheritance:
1. Single Inheritance → One class inherits from another.
2. Multiple Inheritance → A class inherits from multiple classes.
3. Multilevel Inheritance → A class inherits from another class, which is
inherited from another class.
4. Hierarchical Inheritance → One parent class has multiple child classes.
5. Hybrid Inheritance → A combination of multiple types.
Example:
class Parent:
def show(self):
print("Parent class method")
class Child(Parent): # Inherits from Parent
pass
c = Child()
c.show()
6. What is Method Overriding? How does super() help?
Answer:
Method Over riding allows a child class to modify a method inherited from the
parent class. The super() function helps in calling the parent class’s version of
the over ridden method.
Example:
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
super().sound() # Calls Parent's method
print("Barks")
d = Dog()
d.sound()
Output:
Some sound
Barks
7. What is Operator Overloading? Give an example.
Answer:
Operator Overloading allows operators (+, -, *, >, <, etc.) to be redefined for
custom objects.
Example (+ operator for objects):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
retur n Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2 # Uses overloaded `+`
print(p3.x, p3.y) # Output: 4 6
Coding-Based Questions & Solutions
1. Write a Python program to create a class Rectangle and
calculate its area.
Solution:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
retur n self.length * self.width
rect = Rectangle(5, 3)
print("Area:", rect.area()) # Output: 15
2. Create a class Person with name and age attributes and display
their details.
Solution:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
p1 = Person("Alice", 25)
p1.display()
3. Implement Multiple Inheritance with classes A, B, and C.
Solution:
class A:
def methodA(self):
print("Method A")
class B:
def methodB(self):
print("Method B")
class C(A, B): # Multiple Inheritance
def methodC(self):
print("Method C")
obj = C()
obj.methodA()
obj.methodB()
obj.methodC()
4. Create a class Employee with salary attribute and a method to
increase salary.
Solution:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def inc rease_salary(self, amount):
self.salary += amount
e1 = Employee("John", 50000)
e1.inc rease_salary(5000)
print("Updated Salary:", e1.salary) # Output: 55000
5. Create a class BankAccount with deposit and withdraw
functions.
Solution:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Pri vate attribute
def deposit(self, amount):
self.__balance += amount
def withdra w(self, amount):
if self.__balance >= amount:
self.__balance -= amount
else:
print("Insufficient funds")
def get_balance(self):
retur n self.__balance
account = BankAccount(1000)
account.deposit(500)
account.withdra w(300)
print("Final Balance:", account.get_balance()) # Output: 1200
6. Write a Python program to overload the * operator for a custom
class.
Solution:
class Multiply:
def __init__(self, value):
self.value = value
def __mul__(self, other):
retur n Multiply(self.value * other.value)
a = Multiply(4)
b = Multiply(5)
c=a*b
print(c.value) # Output: 20
7. Create a class hierarchy for a vehicle rental system.
Solution:
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def display(self):
print(f"Car Brand: {self.brand}")
car1 = Car("Tesla")
car1.display()