📘 Python Revision Tour – II
2️⃣ Lists in Python
What is a List?
A List is a collection of elements stored in ordered form.
Lists are:
✔ Ordered
✔ Mutable (can be changed)
✔ Allow duplicate values
Example:
marks = [85, 90, 78, 92]
Accessing List Elements
Each element has an index number.
Example:
print(marks[0])
Output
85
Negative Indexing
Python allows accessing elements from the end.
Example
print(marks[-1])
Output
92
List Operations
1. Adding Elements
Using append()
marks.append(95)
Using insert()
marks.insert(1,88)
2. Removing Elements
marks.remove(78)
Remove last element
marks.pop()
3. Updating Elements
marks[2] = 80
3️⃣ List Functions
Function | Purpose |
len() | Number of elements |
max() | Largest value |
min() | Smallest value |
sum() | Total of list |
Example:
numbers = [10,20,30]
print(len(numbers))
print(max(numbers))
print(sum(numbers))
4️⃣ Tuples
What is a Tuple?
A Tuple is a collection similar to list but cannot be modified.
It is immutable.
Example:
t = (10,20,30)
Important points:
✔ Ordered
✔ Allows duplicates
✔ Immutable
Accessing Tuple Elements
t = (5,10,15)
print(t[1])
Output
10
Tuple Functions
Function | Purpose |
len() | number of elements |
max() | maximum value |
min() | minimum value |
Example
t=(5,7,9)
print(len(t))
print(max(t))
5️⃣ Dictionaries
Dictionaries
1. Introduction to Dictionary
A Dictionary in Python is a collection of key–value pairs.
Each element has:
key : value
Example:
student = {
"name": "Rahul",
"age": 17,
"marks": 88
}
Here:
Key | Value |
name | Rahul |
age | 17 |
marks | 88 |
Important Points
✔ Dictionary is mutable (can be changed)
✔ Keys must be unique
✔ Values can be duplicate
✔ Keys must be immutable (string, number, tuple)
2. Creating Dictionaries
Method 1: Using Curly Braces
emp = {
"empid":101,
"name":"Amit",
"salary":45000
}
Method 2: Using dict()
student = dict(name="Riya", age=16, marks=90)
3. Accessing Dictionary Elements
Use key name.
print(student["name"])
Output
Riya
Another method:
print(student.get("marks"))
Difference:
Method | Behaviour |
[] | Error if key not found |
get() | Returns None |
4. Adding Elements to Dictionary
student["city"] = "Mumbai"
Dictionary becomes:
{
'name':'Riya',
'age':16,
'marks':90,
'city':'Mumbai'
}
5. Updating Dictionary Values
student["marks"] = 95
6. Deleting Elements
Using del
del student["age"]
Using pop()
student.pop("city")
Remove last item
student.popitem()
7. Dictionary Functions
len()
Returns number of items.
len(student)
keys()
Returns all keys.
student.keys()
Output
dict_keys(['name','age','marks'])
values()
Returns values.
student.values()
items()
Returns both keys and values.
student.items()
Output
('name','Riya')
('age',16)
('marks',90)
8. Traversing a Dictionary
Using for loop
student = {"name":"Riya","age":16,"marks":90}
for i in student:
print(i, student[i])
Output
name Riya
age 16
marks 90
9. Nested Dictionary
Dictionary inside another dictionary.
Example:
students = {
"101":{"name":"Amit","marks":85},
"102":{"name":"Riya","marks":92}
}
Accessing value:
print(students["101"]["name"])
Output
Amit
10. Applications of Dictionary
Used in:
Phone directory
Student database
Word meaning dictionary
Login systems
Example Phone Directory
phone = {
"Amit":9876543210,
"Riya":9876541234
}
6️⃣ Strings in Python
A String is a sequence of characters.
Example:
name = "Python"
String Operations
Concatenation
a="Hello"
b="World"
print(a+b)
Output
HelloWorld
Repetition
print("Hi"*3)
Output
HiHiHi
String Functions
Function | Purpose |
len() | length of string |
upper() | convert to uppercase |
lower() | convert to lowercase |
find() | search substring |
Example:
name="Python"
print(len(name))
print(name.upper())
No 7️⃣ Python Libraries
A library is a collection of pre-written functions.
Example libraries:
Library | Use |
math | mathematical operations |
random | random numbers |
statistics | statistical calculations |
Example: math Library
import math
print(math.sqrt(25))
Output
5.0
Example: random Library
import random
print(random.randint(1,10))
Output
Random number between 1 and 10
8️⃣ File Handling (Introduction)
File handling allows Python programs to store data permanently.
Example:
file = open("data.txt","w")
file.write("Hello Python")
file.close()
Modes used:
Mode | Meaning |
r | read |
w | write |
a | append |
9️⃣ Sample Programs for Students
Program 1: Find Maximum Number in List
numbers = [10,45,23,67,12]
print("Maximum =",max(numbers))
Program 2: Count Characters in String
text = input("Enter a string:")
print("Length =",len(text))
Program 3: Dictionary Example
student = {"name":"Riya","marks":90}
print(student["marks"])
🔹 1. Functions in Python (Advanced)
📌 Types of Functions
Built-in functions → len(), sum()
User-defined functions
Recursive functions
Anonymous (Lambda) functions
📌 Function Arguments
➤ 1. Required Arguments
def add(a, b):
return a + b
➤ 2. Default Arguments
def greet(name="Guest"):
print("Hello", name)
➤ 3. Keyword Arguments
add(b=5, a=3)
➤ 4. Variable Length Arguments
def total(*args):
return sum(args)
📌 Return Statement
📌 Recursive Function
A function calling itself:
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
📌 Lambda Function
square = lambda x: x*x
🔹 2. File Handling in Python
📌 Types of Files
Text file (.txt)
Binary file (.dat, .bin)
📌 File Modes
| Mode | Description |
|---|
| r | Read |
| w | Write (overwrite) |
| a | Append |
| rb | Read binary |
| wb | Write binary |
📌 Opening & Closing Files
f = open("file.txt", "r")
f.close()
📌 Reading File
f.read()
f.readline()
f.readlines()
📌 Writing File
f.write("Hello")
📌 Append Data
f = open("file.txt", "a")
f.write("New Data")
📌 Using with Statement (Best Practice)
with open("file.txt", "r") as f:
data = f.read()
🔹 3. Working with Binary Files
📌 Using Pickle Module
import pickle
f = open("data.dat", "wb")
pickle.dump([1,2,3], f)
f.close()
📌 Reading Binary File
f = open("data.dat", "rb")
data = pickle.load(f)
🔹 4. Exception Handling
📌 What is Exception?
Runtime error that disrupts program flow
📌 try-except Block
try:
x = int(input())
except ValueError:
print("Invalid input")
📌 Multiple Exceptions
try:
pass
except (ValueError, ZeroDivisionError):
pass
📌 finally Block
finally:
print("Done")
📌 else Block
🔹 5. Modules in Python
📌 What is Module?
A file containing Python code
📌 Importing Modules
import math
math.sqrt(25)
from math import sqrt
📌 Important Modules
📌 Creating User Module
# mymodule.py
def add(a,b):
return a+b
🔹 6. List Manipulation (Advanced)
📌 List Comprehension
squares = [x*x for x in range(5)]
📌 Nested Lists
matrix = [[1,2],[3,4]]
📌 Common Functions
🔹 7. String Manipulation (Advanced)
📌 Important Methods
s.find("a")
s.replace("a","b")
s.split()
s.join()
📌 String Formatting
name = "Bhav"
print(f"Hello {name}")
🔹 8. Python Libraries (Intro)
Examples:
matplotlib → graphs
pandas → data analysis
tkinter → GUI
🔹 9. CSV File Handling
📌 Writing CSV
import csv
f = open("data.csv", "w", newline='')
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
📌 Reading CSV
reader = csv.reader(f)
for row in reader:
print(row)
🔹 10. MySQL Connectivity (Important for CBSE)
📌 Steps:
Install connector
Connect database
Execute query
import mysql.connector
con = mysql.connector.connect(
host="localhost",
user="root",
password="1234",
database="school"
)
📌 Execute Query
cursor = con.cursor()
cursor.execute("SELECT * FROM student")
📌 Fetch Data
data = cursor.fetchall()
📌 Commit Changes
con.commit()
🔹 11. Important Differences
Concept | Difference |
|---|
List vs Tuple | Mutable vs Immutable |
Text vs Binary File | Readable vs Non-readable |
Error vs Exception | Compile vs Runtime |
🧠Important Viva Questions
What is recursion?
Difference between read() and readline()?
What is pickle module?
What is exception handling?
Difference between append and write?
What is CSV file?
What is module?
What is MySQL connector?
📌 Conclusion
Python Revision Tour – II strengthens: