TUPLES and SETS and Further Oxfd
TUPLES and SETS and Further Oxfd
Tuples and sets are built-in data structures in Python used to store collections of
items. They differ in their characteristics and use cases.
Tuples
Tuples are ordered, immutable sequences of items. They are defined using
parentheses () and can contain elements of different data types.
Python
my_tuple = (1, "hello", 3.14)
Sets
Sets are unordered collections of unique elements. They are defined using curly
braces { } or the set() constructor. Sets do not allow duplicate values, and elements
are not stored in any particular order.
Python
my_set = {1, 2, 2, 3}
print(my_set) # Output: {1, 2, 3}
Sets are useful for removing duplicates from a sequence and performing operations
like union, intersection, and difference.
Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
Key Differences
Feature Tuple Set
Ordered Yes No
Mutable No Yes
Defined by () {} or set()
Use Cases
Tuples are suitable for storing fixed collections of items that should not be modified, such as
coordinates, database records, or function arguments.
Sets are useful for tasks involving membership testing, removing duplicates, and performing
set operations.
Sets in Python
Set is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Tuple, and Dictionary, all with different qualities and usage.
Example
Create a Set:
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the
set has been created.
Once a set is created, you cannot change its items, but you can remove
items and add new items.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
The values True and 1 are considered the same value in sets, and are treated as
duplicates:
Example
print(thisset)
The values False and 0 are considered the same value in sets, and are
treated as duplicates:
Example
print(thisset)
Python Set Operations (Union, Intersection, Difference and Symmetric
Difference)
Union of sets
The union of two sets combines all unique elements from both sets.
Syntax:
Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Output
using '|': {1, 2, 3, 4, 5, 6}
using union(): {1, 2, 3, 4, 5, 6}
Note : | operator and union() method both return a new set containing all
unique elements from both sets
Intersection of sets
The intersection of two sets includes only the common elements present in
both sets.
Syntax:
Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Output
using '&': {3, 4}
using intersection(): {3, 4}
Note : & operator and intersection() method return a new set containing
only elements that appear in both sets.
Difference of sets
The difference between two sets includes elements present in the first set but
not in the second.
Syntax:
Example :
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Output
using '-': {1, 2}
using difference(): {1, 2}
Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Output
using '^': {1, 2, 5, 6}
using symmetric_difference(): {1, 2, 5, 6}
# set of letters
s = {'g', 'e', 'k', 's'}
# adding 'f'
s.add('f')
print('Set after updating:', s)
s.clear()
print('\nSet after updating:', s)
Output
Set after updating: {'g', 'k', 's', 'e', 'f'}
Set after updating: {'k', 's', 'e', 'f'}
Set after updating: {'k', 's', 'f'}
Popped element k
Set after updating: {'s', 'f'}
Set after updating: set()
1. File Types
2. Operations on Files (Create, Open, Read, Write, Close)
3. File Names and Paths
4. Format Operator (%)
Python makes it easy to work with files. Whether you're reading data from a
text file or writing to a log file, file handling is a key part of any application.
1. Text Files
2. Binary Files
🔸 Key Differences:
Syntax:
Common Modes:
Mode Description
'r' Read (default), file must exist
'w' Write, creates file or truncates
'a' Append, creates file if not exists
'x' Exclusive creation, error if exists
'b' Binary mode (e.g., 'rb', 'wb')
't' Text mode (default)
'+' Read and write
Example:
Methods:
Example:
✅ D. Writing to a File
file.write("Text to write\n") # Writes a string
file.writelines(["Line1\n", "Line2\n"]) # Writes list of strings
Example:
✅ E. Closing a File
file.close()
🔹 File Paths:
Relative Path:
open("data/info.txt", "r")
Absolute Path:
# Absolute path
abs_path = os.path.abspath("file.txt")
print(abs_path)
🔹 Syntax:
"format string" % (values)
1. .format() Method
Methods:
Functions defined within a class that operate on the object's data. They
define the actions an object can perform.
Constructors:
Special methods (typically named __init__) that are automatically called
when an object is created. They initialize the object's attributes.
Python Class
A class is a collection of objects. Classes are blueprints for creating
objects. A class defines a set of attributes and methods that the created
objects (instances) can have.
Some points on Python class:
Classes are created by keyword class.
Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.)
operator. Example: Myclass.Myattribute
Creating a Class
Here, the class keyword indicates that we are creating a class
followed by name of the class (Dog in this case).
class Dog:
species = "Canine" # Class attribute
Explanation:
class Dog: Defines a class named Dog.
species: A class attribute shared by all instances of the class.
__init__ method: Initializes the name and age attributes when a new
object is created.
Python Objects
class Dog:
species = "Canine" # Class attribute
Output
Buddy
Canine
Explanation:
dog1 = Dog(“Buddy”, 3): Creates an object of the Dog class with
name as “Buddy” and age as 3.
dog1.name: Accesses the instance attribute name of the dog1 object.
dog1.species: Accesses the class attribute species of the dog1 object.
CONSTRUCTORS IN PYTHON
In Python, a constructor is a special method that is called automatically
when an object is created from a class. Its main role is to initialize the
object by setting up its attributes or state.
The method __new__ is the constructor that creates a new instance
of the class while __init__ is the initializer that sets up the instance’s
attributes after creation. These methods work together to manage object
creation and initialization.
__new__ Method
This method is responsible for creating a new instance of a class. It
allocates memory and returns the new object. It is called
before __init__.
class ClassName:
def __new__(cls, parameters):
instance = super(ClassName, cls).__new__(cls)
return instance
__init__ Method
dog1 = Dog("Buddy", 3)
print(dog1.name)
Output
Buddy
Explanation:
__init__: Special method used for initialization.
self.name and self.age: Instance attributes initialized in the
constructor.
def bark(self):
return "Woof!"
When you pass an object to a function, you’re essentially passing a reference to that object.
Depending on the type of object, this may or may not allow the function to modify the
original object.
Explanation
Immutable objects (like int, str, tuple) cannot be changed inside the function. Any
changes create a new object.
Mutable objects (like list, dict, set, and custom class objects) can be changed inside the
function, and those changes affect the original object.
Example 1: Passing a Mutable Object (List)
def add_element(my_list):
my_list.append(4)
print("Inside function:", my_list)
nums = [1, 2, 3]
add_element(nums)
print("Outside function:", nums)
Output:
matlab
CopyEdit
Inside function: [1, 2, 3, 4]
Outside function: [1, 2, 3, 4]
✅ The list was modified inside the function because lists are mutable.
def increment(n):
n += 1
print("Inside function:", n)
x=5
increment(x)
print("Outside function:", x)
Output:
bash
CopyEdit
Inside function: 6
Outside function: 5
Inheritance in Python:
Inheritance is a core concept of object-oriented programming (OOP) that allows one
class (called a child or subclass) to inherit attributes and methods from another class (called
a parent or superclass).
🔸 Syntax of Inheritance
class Parent:
# parent class code
class Child(Parent):
# child class inherits from Parent
d = Dog()
d.speak() # inherited from Animal
d.bark() # defined in Dog
Output:
css
CopyEdit
This animal makes a sound.
Woof!
✅ Dog can access methods from Animal because it inherits from it.
Single Inheritance
In single inheritance, a child class inherits from one parent class.
Example:
class Animal:
def speak(self):
print("Animal speaks")
d = Dog()
d.speak() # Inherited from Animal
d.bark() # Defined in Dog
Output:
Animal speaks
Dog barks
🔹 2. Multiple Inheritance
class Father:
def skills(self):
print("Gardening, Carpentry")
class Mother:
def skills(self):
print("Cooking, Painting")
c = Child()
c.skills()
Output:
rust
CopyEdit
Child's own skills +
Gardening, Carpentry
Cooking, Painting
Multilevel inheritance:
✅ Example:
class Grandparent:
def show_grandparent(self):
print("Grandparent's traits")
class Parent(Grandparent):
def show_parent(self):
print("Parent's traits")
class Child(Parent):
def show_child(self):
print("Child's traits")
c = Child()
c.show_grandparent() # From Grandparent
c.show_parent() # From Parent
c.show_child() # From Child
Output:
rust
CopyEdit
Grandparent's traits
Parent's traits
Child's traits
Multipath inheritance:
Multipath Inheritance occurs when a class inherits from two or more
classes that share a common ancestor. This can lead to ambiguity,
especially when the shared base class has methods or attributes that the child
class might inherit through multiple paths.
Example of Multipath Inheritance
class A:
def show(self):
print("A class method")
class B(A):
def show(self):
print("B class method")
class C(A):
def show(self):
print("C class method")
class D(B, C): # D inherits from both B and C, which both inherit from
A
pass
d = D()
d.show()
Output:
B class method
2. Polymorphism in Python
🔹 Definition:
Polymorphism means “many forms”. In Python, polymorphism allows the
same method or operator to behave differently based on the object it is
acting upon.
🔸 Types of Polymorphism:
1. Function/method polymorphism (same method name, different
behavior)
2. Operator overloading (same operator, different behavior)
# Overload + operator
def __add__(self, other):
return Book(self.pages + other.pages)
def display(self):
print("Total Pages:", self.pages)
# Create two book objects
book1 = Book(150)
book2 = Book(200)
# Display result
book3.display()
Explanation:
The __add__() method is automatically called when book1 + book2 is
used.
It returns a new Book object with combined pages.
UNIT – 4
GU Interface
1. Tkinter Module
import tkinter as tk
3. Layout Management
Tkinter has three layout managers to arrange widgets: pack, grid, and place.
a. pack()
Arranges widgets in blocks before or after each other (top, bottom, left,
right).
Example:
label.pack(side="top")
button.pack(side="left")
b. grid()
label.grid(row=0, column=0)
entry.grid(row=0, column=1)
c. place()
button.place(x=50, y=100)
root = tk.Tk()
root.title("Simple GUI")
entry = tk.Entry(root)
entry.grid(row=0, column=1)
root.mainloop()
Python SQLite
1. Introduction to sqlite3 Module
SQLite is a lightweight, disk-based database. Python’s built-in module sqlite3
allows you to work with SQLite databases easily.
import sqlite3
2. SQLite Methods
a. connect()
Used to connect to an SQLite database file.
If the file does not exist, it will be created.
b. cursor()
Creates a cursor object which is used to execute SQL commands.
cur = conn.cursor()
c. execute()
Executes an SQL query.
cur.execute("SQL QUERY")
d. close()
Closes the database connection.
conn.close()
3. Connecting to a Database
import sqlite3
4. Creating a Table
import sqlite3
conn = sqlite3.connect('school.db')
cur = conn.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
grade TEXT)''')
5. Operations on Tables
a. INSERT Records
import sqlite3
conn = sqlite3.connect('school.db')
cur = conn.cursor()
conn.commit()
print("Records inserted.")
conn.close()
Explanation:
? placeholders are used to safely insert values (prevents SQL injection).
commit() is required to save changes.
b. SELECT Records
import sqlite3
conn = sqlite3.connect('school.db')
cur = conn.cursor()
c. UPDATE Records
import sqlite3
conn = sqlite3.connect('school.db')
cur = conn.cursor()
conn.commit()
print("Record updated.")
conn.close()
Explanation:
Updates Bob's grade to "A+".
d. DELETE Records
import sqlite3
conn = sqlite3.connect('school.db')
cur = conn.cursor()
conn.commit()
print("Record deleted.")
conn.close()
Explanation:
Deletes the record where the name is "Alice".
e. DROP Table
import sqlite3
conn = sqlite3.connect('school.db')
cur = conn.cursor()
conn.commit()
print("Table dropped.")
conn.close()
Explanation:
Removes the entire table and all its data.
Use IF EXISTS to prevent error if the table doesn't exist.
DATA ANALYSIS
NumPy
What is NumPy?
NumPy stands for Numerical Python.
It is used to perform fast mathematical operations on arrays and matrices.
It is much faster than Python lists when it comes to numerical operations.
How to use NumPy?
You need to import the library first:
import numpy as np
Here, np is just a short name (alias) for NumPy.
1. Array Creation
a. From a list or tuple
You can create a NumPy array using a Python list:
a = np.array([1, 2, 3])
print(a)
Explanation:
np.array() converts a list into a NumPy array.
Output: [1 2 3] — it's like a list but optimized for numeric work.
b. Creating a 2D Array (Matrix)
b = np.array([[1, 2], [3, 4]])
print(b)
Explanation:
This creates a 2D array with 2 rows and 2 columns.
Output:
[[1 2]
[3 4]]
c. Using built-in functions
i= np.zeros()
z = np.zeros((2, 3))
print(z)
Explanation:
Creates a 2x3 matrix filled with 0s.
Output:
[[0. 0. 0.]
[0. 0. 0.]]
ii. np.ones()
o = np.ones((2, 2))
print(o)
Explanation:
Creates a 2x2 matrix filled with 1s.
Output:
[[1. 1.]
[1. 1.]]
iii. np.arange(start, stop, step)
r = np.arange(0, 10, 2)
print(r)
Explanation:
Generates numbers from 0 to 10 with a step of 2.
Output: [0 2 4 6 8]
iv. np.linspace(start, stop, num)
l = np.linspace(0, 1, 5)
print(l)
Explanation:
Generates 5 evenly spaced numbers between 0 and 1.
Output: [0. 0.25 0.5 0.75 1. ]
Calculates:
[[1×2 + 2×1, 1×0 + 2×3],
[3×2 + 4×1, 3×0 + 4×3]]
= [[4, 6], [10, 12]]
d. Statistical Functions
a = np.array([1, 2, 3, 4])
print(np.mean(a)) # Average = (1+2+3+4)/4 = 2.5
print(np.max(a)) # Largest value = 4
print(np.min(a)) # Smallest value = 1
print(np.sum(a)) # Total = 10
Pandas in Python
Introduction to Pandas (Python Library)
What is Pandas?
Pandas is a Python library used for working with data.
It helps with:
Organizing data
Analyzing data
Manipulating data
It’s especially useful for working with tabular data (like Excel spreadsheets).
What is a Series?
A Series is a one-dimensional array — like a single column of data.
Example:
import pandas as pd
s = pd.Series([10, 20, 30])
print(s)
Output:
0 10
1 20
2 30
This creates a Series with three values.
Each value has a default index (0, 1, 2).
It's similar to a list, but with labels (index) that Pandas manages.
What is a DataFrame?
A DataFrame is a two-dimensional table — similar to a spreadsheet or SQL
table.
Example:
data = {'Name': ['Amit', 'Riya', 'John'], 'Marks': [88, 92, 79]}
df = pd.DataFrame(data)
print(df)
Output:
Name Marks
0 Amit 88
1 Riya 92
2 John 79
The data dictionary holds columns and values.
Pandas converts this dictionary into a table-like structure.
The index (0, 1, 2) is added automatically.
Matplotlib Library
matplotlib is a powerful Python library for creating static, interactive,
and animated visualizations.
We often use the pyplot module for quick and easy plotting.
1. Line Chart
🔹 Use: To show trends over time or continuous data.
🔹 Code Example:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
plt.plot(x, y)
plt.title("Line Chart")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
🔹 Explanation:
plot(x, y) draws a line through data points.
Useful to show changes or progression.
2. Bar Chart
🔹 Use: To compare categories or groups.
🔹 Code Example:
subjects = ['Math', 'Science', 'English']
marks = [85, 90, 78]
plt.bar(subjects, marks)
plt.title("Student Marks")
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.show()
🔹 Explanation:
bar(x, y) draws vertical bars for each category.
Good for comparing values side-by-side.
3. Histogram
🔹 Use: To show frequency distribution of continuous data.
🔹 Code Example:
ages = [18, 19, 21, 20, 22, 23, 24, 21, 22, 25]
plt.hist(ages, bins=5)
plt.title("Age Distribution")
plt.xlabel("Age")
plt.ylabel("bins1")
plt.show()
🔹 Explanation:
hist(data, bins) groups data into intervals.
Shows how many values fall into each range (bin).
4. Pie Chart
🔹 Use: To show percentage distribution (parts of a whole).
🔹 Code Example:
labels = ['Math', 'Science', 'English']
sizes = [30, 40, 30]