Python OOPS

Python OOP – Fundamentals

Object-Oriented Programming (OOP) is a programming style organized around objects instead of functions.
It helps structure code that is scalable, reusable, and modular.


Four Pillars of OOP

PillarMeaningExample
EncapsulationHiding internal detailsPrivate variables
AbstractionShowing only necessary featuresInterfaces-like behavior
InheritanceAcquiring properties from parent classParent → Child
PolymorphismSame function name, different behaviorMethod overriding

Basic Terminology

TermMeaning
ClassBlueprint/template for an object
ObjectInstance created from a class
MethodA function inside a class
AttributeVariables in a class (properties)
ConstructorInitializes object values (__init__())
class Person:
    def __init__(self, name, age):
        self.name = name    # Instance attribute
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

p1 = Person("Amit", 25)
p1.greet()

Description

  • Person is a class (blueprint).
  • p1 is an object/instance of the class.
  • __init__ is a constructor that initializes object attributes when created.
  • self refers to the current object.
  • greet() is an instance method, accessible using the object.

class Employee:
    company = "Google"  # Class variable (shared by all objects)

    def __init__(self, name):
        self.name = name  # Instance variable (unique to each object)

e1 = Employee("Sam")
e2 = Employee("Riya")
print(e1.company, e2.company)
print(e1.name, e2.name)

Description

  • company belongs to the class, so every Employee object uses “Google”.
  • name is an instance variable — each object has a different value.
  • Helps differentiate data shared across objects and unique to each.

Encapsulation refers to the concept of bundling data and methods that operate on that data into a single unit, i.e., a class. It prevents direct access to data from outside the class and promotes data hiding.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private variable

    def get_balance(self):
        return self.__balance  # Getter method

    def deposit(self, amount):
        self.__balance += amount  # Setter method

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())

Description

  • The variable __balance is private and cannot be accessed directly using object.
  • Encapsulation protects data from accidental modification.
  • We control access through getter & setter functions.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass  # Abstract method (must be implemented)

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14 * self.r * self.r

c = Circle(5)
print(c.area())

Description

  • Shape is an abstract class — cannot be instantiated.
  • Contains an abstract method that forces subclasses to implement it.
  • The Circle must provide its own area method → ensuring a standard structure.

class Sample:
    def __init__(self):
        print("Constructor executed")

    def __del__(self):
        print("Destructor executed")

obj = Sample()
del obj

Description

  • __init__ runs automatically when the object is created.
  • __del__ runs when the object is destroyed or the program ends.
  • Used for resource management (like closing files, DB connections, etc.)

  1. Class Method
  • In Python, a class method is a type of method that is bound to the class itself rather than to instances of the class.
  • It can access and modify class-level attributes and perform actions related to the class as a whole.
  • Class methods are defined using the @classmethod decorator and take the class itself as the first parameter, conventionally named cls.
  • This makes them different from instance methods, which take the instance itself (self) as the first parameter.
  1. Static Method
  • A static method is a method that is defined within a class but is not bound to the class instance or class-level attributes.
  • It doesn’t receive any implicit reference to the class or its instances as parameters. Static methods are defined using the @staticmethod decorator.
  • Static methods are often used to create utility functions that are logically related to the class but don’t require access to instance-specific or class-level data.
class Student:
    school = "DAV School"

    @staticmethod
    def welcome():
        print("Welcome to the School!")  # No object needed

    @classmethod
    def get_school_name(cls):
        return cls.school

Student.welcome()
print(Student.get_school_name())

Description

  • @staticmethod → Does not access class or object data. Used as helper logic.
  • @classmethod → Access class variables using cls.

class Car:
    def __init__(self, brand, model, price):
        self.brand = brand
        self.model = model
        self.price = price

    def details(self):
        print(f"{self.brand} {self.model} costs ₹{self.price}")

c1 = Car("Toyota", "Fortuner", 3500000)
c1.details()

Description

  • Represents real-world entities as Python objects.
  • Helps in designing software similar to real systems.

Python NumPy

Introduction

NumPy is a fundamental library in Python used for scientific computing and data analysis. It stands for “Numerical Python” and provides powerful tools for working with multi-dimensional arrays and matrices, along with a vast collection of mathematical functions to operate on these arrays efficiently.

Slicing and indexing are fundamental operations in NumPy that allow you to access and manipulate specific elements or subsets of an array.

  1. Single Element: You can access a single element of an array by specifying its index using square brackets.
  1. Multiple Elements: You can access multiple elements of an array by passing a list or an array of indices inside the square brackets.
  1. Basic Slicing: You can use slicing to extract a portion of an array by specifying the start and end indices, separated by a colon inside the square brackets.
  1. Step Slicing: You can specify a step value to slice every nth element from the array.
  1. Negative Indices: Negative indices allow you to slice from the end of the array.
  1. Slicing Multi-dimensional Arrays: You can slice multi-dimensional arrays using multiple indexing and slicing operations.

Python Numpy functions

  1. np.array(): Create a NumPy array from a Python list or tuple.
    Syntax: np.array(object, dtype=None, copy=True, order=’K’, subok=False, ndmin=0)
  1. np.arange(): Create an array with evenly spaced values.
    Syntax: np.arange([start,] stop[, step,], dtype=None)
  1. np.zeros(): Create an array filled with zeros.
    Syntax: np.zeros(shape, dtype=float, order=’C’)
  1. np.ones(): Create an array filled with ones.
    Syntax: np.ones(shape, dtype=None, order=’C’)
  1. np.linspace(): Create an array with a specified number of evenly spaced values.
    Syntax: np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
  1. np.eye(): Create an identity matrix.
    Syntax: np.eye(N, M=None, k=0, dtype=float, order=’C’)
  1. np.random.rand(): Generate random values from a uniform distribution.
    Syntax: np.random.rand(d0, d1, …, dn)
  1. np.random.randn(): Generate random values from a standard normal distribution.
    Syntax: np.random.randn(d0, d1, …, dn)
  1. np.random.randint(): Generate random integers within a specified range.
    Syntax: np.random.randint(low, high=None, size=None, dtype=int)

       10. np.shape():  Get the dimensions of an array. Syntax: np.shape(array)

  1. np.reshape(): Reshape an array to a specified shape.
    Syntax: np.reshape(array, newshape, order=’C’)
  1. np.concatenate(): Join arrays along a specified axis.
    Syntax: np.concatenate((array1, array2, …), axis=0)
  1. np.split(): Split an array into multiple sub-arrays.
    Syntax: np.split(array, indices_or_sections, axis=0)
  1. np.max(): Find the maximum value in an array.
    Syntax: np.max(array, axis=None, out=None, keepdims=False, initial=None)
  1. np.min(): Find the minimum value in an array.
    Syntax: np.min(array, axis=None, out=None, keepdims=False, initial=None)
  1. np.mean(): Compute the arithmetic mean of an array.
    Syntax: np.mean(array, axis=None, dtype=None, out=None, keepdims=False)
  1. np.median(): Compute the median of an array.
    Syntax: np.median(array, axis=None, out=None, overwrite_input=False)
  1. np.std(): Compute the standard deviation of an array.
    Syntax: np.std(array, axis=None, dtype=None, out=None, ddof=0, keepdims=False)
  1. np.sum(): Compute the sum of array elements.
    Syntax: np.sum(array, axis=None, dtype=None, out=None, keepdims=False, initial=0)
  1. np.abs():Compute the absolute values of array elements.
    Syntax: np.abs(array)
  1. np.exp(): Compute the exponential of array elements.
    Syntax: np.exp(array)
  1. np.log(): Compute the natural logarithm of array elements.
    Syntax: np.log(array)
  1. np.sin(): Compute the sine of array elements.
    Syntax: np.sin(array)
  1. np.cos(): Compute the cosine of array elements.
    Syntax: np.cos(array)
  1. np.tan(): Compute the tangent of array elements.
    Syntax: np.tan(array)
  1. np.dot(): Compute the dot product of two arrays.
    Syntax: np.dot(a, b, out=None)
  1. np.transpose(): Transpose the dimensions of an array.
    Syntax: np.transpose(array, axes=None)
  1. np.sort(): Sort an array.
    Syntax: np.sort(array, axis=-1, kind=None, order=None)
  1. np.unique(): Find the unique elements of an array.
    Syntax: np.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)
  1. np.argmax(): Find the indices of the maximum values in an array.
    Syntax: np.argmax(array, axis=None, out=None)
  1. np.argmin(): Find the indices of the minimum values in an array.
    Syntax: np.argmin(array, axis=None, out=None)
  1. np.where(): Return the indices of array elements that satisfy a condition.
    Syntax: np.where(condition, x, y)
  1. np.any():Check if any element in an array satisfies a condition.
    Syntax: np.any(array, axis=None, out=None, keepdims=False)
  1. np.all(): Check if all elements in an array satisfy a condition.
    Syntax: np.all(array, axis=None, out=None, keepdims=False)
  1. np.isnan(): Check for NaN (Not a Number) values in an array.
    Syntax: np.isnan(array)
  1. np.logical_and(): Perform element-wise logical AND operation on arrays.
    Syntax: np.logical_and(array1, array2)
  1. np.logical_or(): Perform element-wise logical OR operation on arrays.
    Syntax: np.logical_or(array1, array2)
  1. np.logical_not(): Perform element-wise logical NOT operation on an array.
    Syntax: np.logical_not(array)
  1. np.sinh(): Compute the hyperbolic sine of array elements.
    Syntax: np.sinh(array)
  1. np.cosh(): Compute the hyperbolic cosine of array elements.
    Syntax: np.cosh(array)
  1. np.tanh(): Compute the hyperbolic tangent of array elements.
    Syntax: np.tanh(array)
  1. np.arcsin(): Compute the inverse sine of array elements.
    Syntax: np.arcsin(array)
  1. np.arccos(): Compute the inverse cosine of array elements.
    Syntax: np.arccos(array)
  1. np.arctan(): Compute the inverse tangent of array elements.
    Syntax: np.arctan(array)
  1. np.pi: A constant representing the value of pi (π). A constant representing the value of pi (π)

        46. np.e: A constant representing the value of Euler’s number (e). A constant representing the value of Euler’s number (e)

  1. np.log10(): Compute the base-10 logarithm of array elements.
    Syntax: np.log10(array)
  1. np.floor(): Round down array elements to the nearest integer.
    Syntax: np.floor(array)
  1. np.ceil(): Round up array elements to the nearest integer.
    Syntax: np.ceil(array)
  1. np.isclose(): Check if two arrays are element-wise approximately equal.
    Syntax: np.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

      51. np.correlate(): Compute the cross-correlation of two arrays.
Syntax: np.correlate(a, v, mode=’valid’)

  1. np.cov(): Compute the covariance matrix of an array.
    Syntax: np.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)

Python Pandas

Python Pandas Tutorial

Introduction

Pandas is a popular open-source data manipulation and analysis library for Python. It provides easy-to-use data structures and data analysis tools, making it an essential tool for data scientists and analysts.

Pandas introduces two main data structures: Series and DataFrame. A Series is a one-dimensional labeled array capable of holding any data type. It is similar to a column in a spreadsheet or a single column of a database table. On the other hand, a DataFrame is a two-dimensional labeled data structure that resembles a spreadsheet or a SQL table. It consists of multiple columns, each of which can hold different data types.

With Pandas, you can perform a wide range of data operations, such as loading and saving data from various file formats (e.g., CSV, Excel, SQL databases), cleaning and preprocessing data, manipulating and transforming data, merging and joining datasets, aggregating and summarizing data, and performing statistical analysis.

Pandas provides a rich set of functions and methods to handle data effectively. It allows you to filter, sort, and group data, compute descriptive statistics, handle missing values, apply mathematical and statistical operations, and create visualizations. Additionally, Pandas integrates well with other popular Python libraries like NumPy, Matplotlib, and scikit-learn, enabling seamless integration into a data analysis or machine learning workflow.

Features of Python Pandas

  1. Data Structures: Pandas provides two main data structures, Series and DataFrame, that allow for efficient handling of structured data. Series represents a one-dimensional array with labeled indices, while DataFrame represents a two-dimensional table-like structure with labeled rows and columns.
  2. Data Manipulation: Pandas offers a wide range of functions and methods to manipulate and transform data. You can filter, sort, and slice data, add or remove columns, reshape data, handle missing values, and perform various data transformations.
  3. Data Loading and Saving: Pandas supports reading and writing data from various file formats, including CSV, Excel, SQL databases, and more. It provides convenient functions to load data from files into a DataFrame and save DataFrame contents back to files.
  4. Data Cleaning and Preprocessing: Pandas helps in cleaning and preprocessing data by providing methods to handle missing values, handle duplicate data, handle outliers, and perform data imputation. It also allows for data type conversion, string manipulation, and other data cleaning operations.
  5. Data Aggregation and Grouping: Pandas enables efficient data aggregation and grouping operations. You can group data based on specific criteria, calculate summary statistics (e.g., mean, sum, count) for each group, and perform advanced aggregation tasks using custom functions.
  6. Data Merging and Joining: Pandas provides powerful tools for combining and merging data from different sources. It allows you to join multiple DataFrames based on common columns, perform database-style merging operations (e.g., inner join, outer join), and concatenate DataFrames vertically or horizontally.
  7. Time Series Analysis: Pandas has excellent support for working with time series data. It offers functionalities for time-based indexing, time series resampling, frequency conversion, date range generation, and handling time zones.
  8. Efficient Computation: Pandas is designed to handle large datasets efficiently. It utilizes optimized algorithms and data structures, which enable fast data processing and computation. Additionally, Pandas integrates well with other numerical libraries like NumPy, enabling seamless integration into scientific computing workflows.
  9. Data Visualization: While not a primary focus, Pandas integrates with popular visualization libraries such as Matplotlib and Seaborn. It provides convenient functions to create various plots and visualizations directly from DataFrame objects.
  10. Integration with Ecosystem: Pandas integrates well with the broader Python data analysis ecosystem. It can be used in conjunction with libraries like NumPy, Matplotlib, scikit-learn, and others, allowing for seamless integration into data analysis, machine learning, and scientific computing workflows.

Advantages of Python Pandas

  1. Easy Data Manipulation: Pandas provides intuitive and easy-to-use data structures and functions that simplify data manipulation tasks. It offers a high-level interface to filter, transform, aggregate, and reshape data, making it convenient to clean and preprocess datasets.
  2. Efficient Data Handling: Pandas is designed for efficient handling of structured data. It leverages optimized data structures and algorithms, enabling fast and efficient operations on large datasets. This efficiency is crucial when working with big data or performing complex computations.
  3. Data Alignment: One of the powerful features of Pandas is data alignment. It automatically aligns data based on labeled indices, ensuring that operations are performed on corresponding data elements. This simplifies data analysis tasks and reduces the chances of errors.
  4. Missing Data Handling: Pandas provides robust tools for handling missing data. It allows you to identify, handle, and impute missing values in a flexible manner. You can choose to drop missing values, fill them with specific values, or perform more sophisticated imputation techniques.
  5. Data Aggregation and Grouping: Pandas makes it easy to perform data aggregation and grouping operations. You can group data based on specific criteria, calculate summary statistics for each group, and apply custom aggregation functions. This is particularly useful for generating insights from categorical or grouped data.
  6. Data Input and Output: Pandas supports a wide range of file formats for data input and output, including CSV, Excel, SQL databases, and more. It simplifies the process of loading data from external sources and saving processed data back to different formats, facilitating seamless integration with other tools and workflows.
  7. Time Series Analysis: Pandas provides excellent support for time series analysis. It offers functionalities for time-based indexing, resampling, frequency conversion, and handling time zones. This makes it a valuable tool for analyzing and working with temporal data.
  8. Integration with Ecosystem: Pandas integrates seamlessly with other popular Python libraries, such as NumPy, Matplotlib, scikit-learn, and more. It enables smooth interoperability between different tools and allows you to leverage the capabilities of the broader data analysis ecosystem.
  9. Flexibility and Customization: Pandas is highly flexible and customizable. It provides a rich set of functions and options that allow you to tailor your data analysis tasks to specific requirements. You can apply custom functions, create derived variables, and define complex data transformations.
  10. Active Community and Resources: Pandas has a vibrant and active community of users and contributors. This means there are abundant online resources, tutorials, and examples available to help you learn and solve data analysis problems. The community support ensures that Pandas stays up-to-date and continuously improves.

Disadvantages of Python Pandas

  1. Memory Usage: Pandas can be memory-intensive, especially when working with large datasets. The underlying data structures used by Pandas, such as DataFrames, can consume a significant amount of memory. This can become a limitation when working with extremely large datasets that cannot fit into memory.
  2. Execution Speed: Although Pandas provides efficient data handling, it may not always be the fastest option for data processing. Certain operations in Pandas, especially those involving iterations or complex calculations, can be slower compared to lower-level libraries like NumPy. For performance-critical tasks, using specialized libraries or optimizing the code might be necessary.
  3. Learning Curve: Pandas has a steep learning curve, particularly for users who are new to Python or data manipulation. Understanding the underlying concepts of data structures, indexing, and the various functions and methods available in Pandas requires time and practice. Users may need to invest time in learning Pandas to effectively utilize its capabilities.
  4. Data Size Limitations: Pandas might not be suitable for working with extremely large datasets that exceed the available memory capacity. When dealing with big data scenarios, alternative solutions such as distributed computing frameworks (e.g., Apache Spark) or databases might be more appropriate.
  5. Limited Support for Non-Tabular Data: Pandas is primarily designed for working with structured, tabular data. It may not provide comprehensive support for working with non-tabular data types, such as unstructured text data or complex hierarchical data structures. In such cases, specialized libraries or tools might be more suitable.
  6. Lack of Native Parallelism: Pandas operations are predominantly executed in a single thread, which can limit performance when dealing with computationally intensive tasks. Although there are ways to parallelize certain operations in Pandas using external libraries or techniques, it requires additional effort and may not always be straightforward.
  7. Potential for Error: Due to the flexibility and numerous functions available in Pandas, there is a potential for errors and inconsistencies in data analysis workflows. Incorrect usage of functions, improper data alignment, or misunderstanding of concepts can lead to unintended results. Careful attention to data validation and verification is essential to ensure accurate analysis.
  8. Limited Visualization Capabilities: While Pandas integrates with visualization libraries like Matplotlib and Seaborn, its built-in visualization capabilities are not as extensive as those provided by dedicated visualization tools like Tableau or Plotly. For complex and advanced visualizations, additional tools or libraries may be required.

Data Structures in Python Pandas

  1. Series:

 A Series is a one-dimensional labeled array capable of holding any data type. It is similar to a column in a spreadsheet or a single column of a database table. A Series consists of two components: the data itself and the associated labels, known as the index. The index provides a way to access and manipulate the data elements. Series can be created from various sources like lists, arrays, dictionaries, or other Series.

  1. DataFrame:

 A DataFrame is a two-dimensional labeled data structure, resembling a spreadsheet or a SQL table. It consists of multiple columns, each of which can hold different data types. DataFrames have both row and column labels, allowing for easy indexing and manipulation. DataFrames can be thought of as a collection of Series, where each column represents a Series. DataFrames can be created from various sources, such as dictionaries, lists, arrays, or importing data from external files.

Python Pandas function

First import the pandas library and a CSV file to perform following operations on it.

				
					# Example: 
Import pandas as pd 
Data = pd.read_csv(“file name.csv)

				
			

DataFrame function

1. `head(n)`: Returns the first n rows of the DataFrame.

				
					# Example: 
df.head(5)

				
			
  1. `tail(n)`: Returns the last n rows of the DataFrame.
				
					# Example:
df.tail(5)

				
			
  1. `shape`: Returns the dimensions of the DataFrame.
				
					# Example:
df.shape

				
			
  1. `describe()`: Generates descriptive statistics of the DataFrame.
				
					# Example:
df.describe()

				
			
  1. `info()`: Provides a summary of the DataFrame’s structure and data types.
				
					# Example:
df.info()

				
			
  1. `columns`: Returns the column names of the DataFrame.
				
					# Example:
df.columns

				
			
  1. `dtypes`: Returns the data types of the columns.
				
					# Example:
df.dtypes

				
			
  1. `astype(dtype)`: Converts the data type of a column.
				
					# Example:
df['column_name'] = df['column_name'].astype(dtype)

				
			
  1. `drop(labels, axis)`: Drops specified rows or columns from the DataFrame.
				
					# Example:
df.drop(['column_name'], axis=1)

				
			

10. `sort_values(by, ascending)`: Sorts the DataFrame by specified columns.

				
					# Example:
df.sort_values(by='column_name', ascending=True)

				
			
  1. `groupby(by)`: Groups the DataFrame by specified column(s).
				
					# Example:
df.groupby('column_name')

				
			

12. `agg(func)`: Applies an aggregate function to grouped data.

				
					# Example:
df.groupby('column_name').agg({'column_name': 'aggregate_func'})

				
			
  1. `merge(df2, on)`: Merges two DataFrames based on a common column.
				
					# Example:
df.merge(df2, on='column_name')

				
			
  1. `pivot_table(values, index, columns, aggfunc)`: Creates a pivot table based on specified values, index, and columns.
				
					# Example:
pd.pivot_table(df, values='column_name', index='index_column', columns='column_name', aggfunc='aggregate_func')

				
			
  1. `fillna(value)`: Fills missing values in the DataFrame.
				
					# Example:
df.fillna(value)

				
			
  1. `drop_duplicates(subset)`: Drops duplicate rows from the DataFrame.
				
					# Example:
df.drop_duplicates(subset=['column_name'])

				
			
  1. `sample(n)`: Returns a random sample of n rows from the DataFrame.
				
					# Example:
df.sample(n=5)

				
			
  1. `corr()`: Computes the correlation between columns in the DataFrame.
				
					# Example:
df.corr()

				
			
  1. `apply(func)`: Applies a function to each element or row/column of the DataFrame.
				
					# Example:
df['column_name'].apply(func)

				
			
  1. `to_csv(file_path)`: Writes the DataFrame to a CSV file.
				
					# Example:
df.to_csv('file_path.csv', index=False)

				
			
  1. `to_excel(file_path)`: Writes the DataFrame to an Excel file.
				
					# Example:
df.to_excel('file_path.xlsx', index=False)

				
			

22. `to_json(file_path)`: Writes the DataFrame to a JSON file.

				
					# Example:
df.to_json('file_path.json', orient='records')

				
			

Series Functions

  1. `values`: Returns the values of the Series.
				
					# Example:
series.values

				
			
  1. `index`: Returns the index of the Series.
				
					# Example: 
series.index

				
			
  1. `unique()`: Returns unique values in the Series.
				
					# Example:
series.unique()

				
			
  1. `nunique()`: Returns the number of unique values in the Series.
				
					# Example:
series.nunique()

				
			
  1. `sort_values(ascending)`: Sorts the Series.
				
					# Example:
series.sort_values(ascending=True)

				
			
  1. `max()`: Returns the maximum value in the Series.
				
					# Example:
series.max()

				
			
  1. `min()`: Returns the minimum value in the Series.
				
					# Example:
series.min()

				
			
  1. `mean()`: Returns the mean of the Series.
				
					# Example:
series.mean()

				
			
  1. `median()`: Returns the median of the Series.
				
					# Example:
series.median()

				
			
  1. `sum()`: Returns the sum of the Series.
				
					# Example:
series.sum()

				
			
  1. `count()`: Returns the number of non-null values in the Series.
				
					# Example:
series.count()

				
			
  1. `isnull()`: Checks for missing values in the Series.
				
					# Example:
series.isnull()

				
			
  1. `fillna(value)`: Fills missing values in the Series.
				
					# Example:
series.fillna(value)

				
			
  1. `drop_duplicates()`: Drops duplicate values from the Series.
				
					# Example:
series.drop_duplicates()

				
			
  1. `apply(func)`: Applies a function to each element of the Series.
				
					# Example:
series.apply(func)

				
			
  1. `map(dict)`: Maps values in the Series using a dictionary.
				
					# Example:
series.map(dict)

				
			
  1. `replace(to_replace, value)`: Replaces values in the Series with another value.
				
					# Example:
series.replace(to_replace, value)

				
			
  1. `between(start, end)`: Checks if values in the Series are between a range.
				
					# Example:
series.between(start, end)

				
			
  1. `astype(dtype)`: Converts the data type of the Series.
				
					# Example:
series.astype(dtype)

				
			

Slicing and indexing using Pandas

Slicing and indexing in Python Pandas allow you to extract specific subsets of data from a DataFrame or Series.

  1. Indexing with Square Brackets:

– Accessing a single column:

				
					df['column_name']
				
			

– Accessing multiple columns:

				
					df[['column_name1', 'column_name2']]
				
			

– Accessing rows by index label:

				
					df.loc[index_label]
				
			

– Accessing rows by integer index position:

				
					df.iloc[index_position]
				
			
  1. Slicing with Square Brackets:

– Slicing rows based on index labels:

				
					df[start_label:end_label]
				
			

– Slicing rows based on index positions:

				
					=df[start_position:end_position]
				
			

– Slicing rows and columns:

				
					df[start_row:end_row, start_column:end_column]
				
			
  1. Conditional Indexing:

– Selecting rows based on a condition:

				
					df[df['column_name'] > value]
				
			

– Selecting rows based on multiple conditions:

				
					df[(df['column_name1'] > value1) & (df['column_name2'] < value2)]
				
			
  1. Boolean Indexing:

– Creating a Boolean mask:

				
					mask = df['column_name'] > value

				
			

– Applying the Boolean mask to the DataFrame:

				
					df[mask]
				
			
  1. Setting Index:

– Setting a column as the index:

				
					df.set_index('column_name')
				
			
  1. Resetting Index:

– Resetting the index:

				
					df.reset_index()
				
			

These are some common techniques for slicing and indexing data in Python Pandas. They allow you to retrieve specific columns, rows, or subsets of data based on various conditions and positions. By leveraging these indexing methods, you can efficiently extract and manipulate the data you need for further analysis or processing.

Conclusion

In conclusion, Pandas is a powerful library in Python for data manipulation, analysis, and exploration. It offers a variety of functions and methods to read and write data from different file formats, perform data exploration and manipulation, handle missing values, and aggregate data

Overall, Pandas is a versatile and indispensable tool for data analysis and manipulation in Python. It simplifies the data handling process, offers a wide range of functionalities, and enhances productivity in various data-related tasks, including data preprocessing, exploratory data analysis, feature engineering, and machine learning.

Python File Handling

Introduction

File handling in Python is a fundamental concept that allows you to read from and write to files on your computer.

Opening a file: To open a file, you can use the built-in open() function. It takes two arguments: the file path (including the file name) and the mode in which you want to open the file.

In Python, file handling modes are used to specify the intended operation when opening a file. Each mode determines whether the file should be opened for reading, writing, appending, or exclusive creation. Here are the different modes in Python file handling without plagiarism:

This is the default mode when opening a file. It allows you to read the contents of an existing file. If the file does not exist, a `FileNotFoundError` will be raised.

Write mode opens a file for writing. If the file exists, it truncates (empties) the file before writing to it. If the file does not exist, a new file is created. Be cautious because opening a file in write mode will erase its previous contents.

Append mode opens a file for appending new data at the end. If the file exists, the data will be added to the existing content. If the file does not exist, a new file is created.

Exclusive creation mode opens a file for writing but only if the file does not already exist. If the file exists, a `FileExistsError` is raised.

Binary mode is an optional flag that can be added to any of the above modes. It is used when working with binary files, such as images or audio files. This mode ensures proper handling of binary data.


A context manager in Python to open a file ensures that the file is automatically closed after use — even if an error occurs. This prevents resource leaks and makes the code cleaner.

It’s important to note that using the `with` statement is recommended when working with files, as it automatically takes care of closing the file, even if an exception occurs. Here’s an example using the `with` statement:


  1. `read()` method:

The `read()` method is used to read the entire contents of a file as a single string. Here’s an example:

  1. `readline()` method:

The `readline()` method is used to read a single line from a file. Here’s an example:

  1. `readlines()` method:

The `readlines()` method reads all the lines of a file and returns them as a list of strings. Here’s an example:

  1. `write()` method:

The `write()` method is used to write a string to a file. Here’s an example:

  1. `writelines()` method:

The `writelines()` method is used to write a list of strings to a file, where each string represents a line. Here’s an example:

  1. `seek()` method:

The `seek()` method is used to change the file’s current position to the given offset. Here’s an example:

  1. `tell()` method:

The `tell()` method is used to return the current position of the file pointer. Here’s an example:

Python Lambda Function

Python Lambda Function Tutorial

Python Lambda Functions ( Anonymous function )

Anonymous functions in Python, also known as lambda functions, allow you to create small, one-line functions without explicitly defining a function using the `def` keyword.

Syntax: `lambda arguments: expression`

The `lambda` keyword is used to define a lambda function. It is followed by the arguments (comma-separated) and a colon (:), then the expression that is evaluated and returned as the function’s result. Here is an example:

				
					# Creating a lambda function to add two numbers
add_numbers = lambda x, y: x + y

# Calling the lambda function
result = add_numbers(10, 15)
print(result)  # Output: 25

				
			

In this example, we define a lambda function `add_numbers` that takes two arguments, `x` and `y`. The function adds these two numbers together using the `+` operator and returns the result. We then call the lambda function by providing the arguments `10` and `15`, and store the returned value in the `result` variable.

Lambda functions are commonly used when you need a simple, one-line function and don’t want to define a separate named function. They are often used in combination with built-in functions like `map()`, `filter()`, and `reduce()` to perform operations on iterables in a concise and readable manner.

Features of Python Lambda Functions:

  1. Anonymity: Lambda functions do not have a name, making them useful for short, simple operations where defining a separate function using def is not necessary.
  2. Compactness: Lambda functions are typically concise and can be defined in a single line.
  3. Single Expression: Lambda functions are limited to a single expression, which means they cannot contain multiple statements or complex logic.
  4. Functional Programming: Lambda functions are commonly used in functional programming to pass behavior as arguments to higher-order functions like map, filter, and reduce.

Difference between Built-in functions and Lambda functions (also known as Anonymous functions)

In Python, the main difference between built-in functions and anonymous functions (also known as lambda functions) lies in their structure, creation, and usage.

Built-in Functions:

Built-in functions in Python are pre-defined functions that are provided by the Python language itself. They are readily available for use without any additional coding or import statements. These functions cover a wide range of tasks and operations, such as mathematical calculations, string manipulations, list operations, file I/O, etc. They are named and can be used repeatedly throughout the code. Here’s an example of using a built-in function to find the length of a list:

				
					# Using the built-in function len() to find the length of a list
numbers = [1, 2, 3, 4, 5]
length = len(numbers)
print(length)  # Output: 5

				
			

In this example, the len() function is a built-in function that returns the number of elements in the list numbers.

Lambda Functions (Anonymous Functions):

Lambda functions are a special type of function in Python that allows you to create small, one-line functions without explicitly defining them using the def keyword. Lambda functions are typically used for simple, one-time tasks and are often used in conjunction with higher-order functions like map(), filter(), and reduce().

Lambda functions have the following structure: lambda arguments: expression

The lambda function takes a set of arguments, performs the specified expression on those arguments, and returns the result of the expression. Here’s an example of a lambda function that calculates the square of a number:

				
					# Using a lambda function to calculate the square of a number
square = lambda x: x**2
result = square(5)
print(result)  # Output: 25

				
			

In this example, we create a lambda function that takes an argument x, calculates the square using the expression x**2, and then we call the lambda function with square(5) to calculate the square of 5.

Key Differences:

  1. Structure and Definition: Built-in functions are predefined and come with Python, whereas lambda functions are created on-the-fly and are not explicitly defined using the def keyword.
  2. Usage and Complexity: Built-in functions are used for a wide range of tasks and can be complex with multiple parameters, whereas lambda functions are typically used for simple operations with one or few parameters.
  3. Naming: Built-in functions have names, and you can call them using their names whenever needed. Lambda functions, on the other hand, do not have names and are often used as temporary, inline functions.
  4. Return Statement: Built-in functions return their results as any other function, using the return statement. Lambda functions automatically return the value of the expression without using the return statement.
  5. Use Cases: Built-in functions are ideal for general-purpose and reusable tasks, while lambda functions are more suited for immediate, short-term, and one-time uses.

Python Built In Functions

Python Built In Functions

Introduction

Python is a powerful and versatile programming language that comes with a rich set of built-in functions. These functions are pre-defined and readily available, making it easier for developers to accomplish various tasks without having to write the code from scratch. In this tutorial, we will explore what built-in functions are in Python, provide examples of some commonly used built-in functions, and explain the difference between built-in functions and user-defined functions.

What are Built-in Functions in Python?

Built-in functions are functions that are built into the Python programming language. They are always available and do not require any additional installations or imports. These functions are designed to perform common tasks and operations on different types of data. Python provides a wide range of built-in functions, which can be broadly categorized into the following types:

  1. Mathematical Functions: These functions perform various mathematical operations such as calculating absolute values, rounding numbers, finding maximum and minimum values, and more.
  2. String Functions: String functions handle operations on strings, such as concatenation, case conversions, finding substrings, and more.
  3. List Functions: List functions deal with operations on lists, including sorting, adding elements, removing elements, and more.
  4. Dictionary Functions: These functions work with dictionaries, enabling operations like accessing keys, values, merging dictionaries, etc.
  5. File Input/Output Functions: File-related functions help in reading from and writing to files.
  6. Type Conversion Functions: Type conversion functions allow you to convert data from one type to another, such as converting integers to strings or vice versa.
  7. Other Utility Functions: Python also provides several other utility functions for tasks like input/output, formatting, etc.

Now, let’s explore some examples of commonly used built-in functions in Python.

Examples of Python Built-in Functions:

  1. Mathematical Functions:
				
					# Absolute value
abs_result = abs(-10)	
print(abs_result)  # Output: 10

# Rounding
round_result = round(3.14159, 2)
print(round_result)  # Output: 3.14

# Maximum and Minimum
max_result = max(5, 9, 3, 7)
print(max_result)  # Output: 9

min_result = min(5, 9, 3, 7)
print(min_result)  # Output: 3

				
			
  1. String Functions:
				
					# Concatenation
str1 = "Hello"
str2 = "World"
concatenated_str = str1 + " " + str2
print(concatenated_str)  # Output: "Hello World"

# Upper and Lower case
text = "Python is Amazing"
uppercase_text = text.upper()
lowercase_text = text.lower()
print(uppercase_text)  # Output: "PYTHON IS AMAZING"
print(lowercase_text)  # Output: "python is amazing"

# Finding substring
sentence = "Python programming is fun"
substring = "programming"
index = sentence.find(substring)
print(index)  # Output: 7

				
			
  1. List Functions:
				
					# Sorting
numbers = [5, 2, 8, 1, 3]
numbers.sort()
print(numbers)  # Output: [1, 2, 3, 5, 8]

# Appending elements
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)  # Output: ['apple', 'banana', 'orange']

# Removing elements
fruits.remove("banana")
print(fruits)  # Output: ['apple', 'orange']

				
			
  1. Dictionary Functions:
				
					# Accessing keys and values
student_scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
keys = student_scores.keys()
values = student_scores.values()
print(keys)  # Output: dict_keys(['Alice', 'Bob', 'Charlie'])
print(values)  # Output: dict_values([85, 92, 78])

# Merging dictionaries
more_scores = {"David": 88, "Eva": 95}
student_scores.update(more_scores)
print(student_scores)
# Output: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88, 'Eva': 95}

				
			
  1. File Input/Output Functions:
				
					# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, this is an example file.")

# Reading from a file
with open("example.txt", "r") as file:
    content = file.read()
print(content)  # Output: "Hello, this is an example file."

				
			

Difference Between Built-in Functions and User-defined Functions:

The primary difference between built-in functions and user-defined functions lies in their origin and availability. Built-in functions are provided by the Python language itself and are readily available for use without any additional code. On the other hand, user-defined functions are created by the developers themselves to perform specific tasks and are not available in the language by default. Here’s an example to illustrate the difference:

User-defined Function:

				
					def square(x):
    return x ** 2

result = square(5)
print(result)  # Output: 25

				
			

Built-in Function:

				
					num_list = [2, 4, 6, 8, 10]
sum_result = sum(num_list)
print(sum_result)  # Output: 30

				
			

In the user-defined function example, we define a function called “square” that takes a parameter “x” and returns its square. In the built-in function example, we use the “sum” function, which is already provided by Python, to calculate the sum of the elements in the list.

Difference between Built-in functions and anonymous functions (also known as lambda functions)

In Python, the main difference between built-in functions and anonymous functions (also known as lambda functions) lies in their structure, creation, and usage.

Built-in Functions:

Built-in functions in Python are pre-defined functions that are provided by the Python language itself. They are readily available for use without any additional coding or import statements. These functions cover a wide range of tasks and operations, such as mathematical calculations, string manipulations, list operations, file I/O, etc. They are named and can be used repeatedly throughout the code. Here’s an example of using a built-in function to find the length of a list:

				
					# Using the built-in function len() to find the length of a list
numbers = [1, 2, 3, 4, 5]
length = len(numbers)
print(length)  # Output: 5

				
			

In this example, the len() function is a built-in function that returns the number of elements in the list numbers.

Anonymous Functions (Lambda Functions):

Lambda functions are a special type of function in Python that allows you to create small, one-line functions without explicitly defining them using the def keyword. Lambda functions are typically used for simple, one-time tasks and are often used in conjunction with higher-order functions like map(), filter(), and reduce(). Lambda functions have the following structure: lambda arguments: expression

The lambda function takes a set of arguments, performs the specified expression on those arguments, and returns the result of the expression. Here’s an example of a lambda function that calculates the square of a number:

				
					# Using a lambda function to calculate the square of a number
square = lambda x: x**2
result = square(5)
print(result)  # Output: 25

				
			

In this example, we create a lambda function that takes an argument x, calculates the square using the expression x**2, and then we call the lambda function with square(5) to calculate the square of 5.

Key Differences:

  1. Structure and Definition: Built-in functions are predefined and come with Python, whereas lambda functions are created on-the-fly and are not explicitly defined using the def keyword.
  2. Usage and Complexity: Built-in functions are used for a wide range of tasks and can be complex with multiple parameters, whereas lambda functions are typically used for simple operations with one or few parameters.
  3. Naming: Built-in functions have names, and you can call them using their names whenever needed. Lambda functions, on the other hand, do not have names and are often used as temporary, inline functions.
  4. Return Statement: Built-in functions return their results as any other function, using the return statement. Lambda functions automatically return the value of the expression without using the return statement.
  5. Use Cases: Built-in functions are ideal for general-purpose and reusable tasks, while lambda functions are more suited for immediate, short-term, and one-time uses.

Python List Vs Tuple

Introduction

Python offers a wide range of data structures to store and manipulate collections of data. Two commonly used data structures are lists and tuples. Both lists and tuples are sequences that can hold multiple elements, but they have distinct characteristics and use cases.

List

In Python, a list is a versatile and fundamental data structure that serves as a collection of elements in a specific order. It allows you to store multiple values of different data types, such as numbers, strings, or even other lists, within a single container. Lists are enclosed within square brackets [ ] and elements inside the list are separated by commas.

Examples of a List:

numbers = [1, 2, 3, 4, 5]

#Example 2: A list of strings
fruits = ["apple", "banana", "cherry", "date"]

#Example 3: A mixed list containing different data types
mixed_list = [42, "hello", 3.14, True]

Tuple

In Python, a tuple is an ordered and immutable collection of elements. It is a data structure that allows you to store multiple items of different data types within a single object. Tuples are defined using parentheses () and can hold elements separated by commas. Once a tuple is created, its elements cannot be changed or modified, making it an immutable data type.

Example of a Tuple:

# Example 1: A tuple of integers
numbers = (1, 2, 3, 4, 5)

# Example 2: A tuple of strings
fruits = ("apple", "banana", "cherry", "date")

# Example 3: A mixed tuple containing different data types
mixed_tuple = (42, "hello", 3.14, True)

Main Differences between Lists and Tuples:

  1. Mutability:

List: Lists are mutable, meaning you can modify their elements after creation. You can add, remove, or change elements within a list.

Tuple: Tuples, on the other hand, are immutable. Once a tuple is created, its elements cannot be modified. You cannot add, remove, or change elements in a tuple.

# List example
my_list = [1, 2, 3]
my_list[0] = 10 # Modify an element
my_list.append(4) # Add an element
my_list.remove(2) # Remove an element
print(my_list) # Output: [10, 3, 4]
------------------------------------------------------
# Tuple example
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # This will raise a TypeError
# my_tuple.append(4) # This will raise an AttributeError
print(my_tuple) # Output: (1, 2, 3)
  1. Syntax:

List: Lists are enclosed in square brackets [ ]. Elements inside the list are separated by commas.

Tuple: Tuples are enclosed in parentheses ( ). Elements inside the tuple are separated by commas.

# List Example
my_list = [10, 20, 30, 40] # A list of integers
names = ["Alice", "Bob", "Charlie"] # A list of strings
mixed_list = [1, "hello", 3.14] # A mixed list
-------------------------------------------------------------
# Tuple Example
my_tuple = (10, 20, 30, 40) # A tuple of integers
names_tuple = ("Alice", "Bob", "Charlie") # A tuple of strings
mixed_tuple = (1, "hello", 3.14) # A mixed tuple
  1. Performance:

List: Lists might have slightly lower performance compared to tuples due to their mutability. Modifying a list can require resizing and memory allocation.

Tuple: Tuples, being immutable, have better performance than lists, especially in scenarios where elements remain constant.

import time

# Creating a list and a tuple
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)

# Measuring access time for the list
start_time = time.time()
for _ in range(1_000_000):
_ = my_list[2] # Accessing the third element
list_time = time.time() - start_time

# Measuring access time for the tuple
start_time = time.time()
for _ in range(1_000_000):
_ = my_tuple[2] # Accessing the third element
tuple_time = time.time() - start_time

# Printing results
print(f"List Access Time: {list_time:.6f} seconds")
print(f"Tuple Access Time: {tuple_time:.6f} seconds")
  1. Use Cases:

List: Lists are ideal when you need to store collections of items that can change over time, such as dynamic data or mutable sequences.

Tuple: Tuples are suitable for situations where you want to ensure data remains constant and unchangeable, like storing coordinates, configuration settings, or database records.


  1. Ordered Collection: Both lists and tuples are ordered collections, meaning the elements are stored in a specific sequence, and the order of elements is preserved.
  2. Indexing: Both lists and tuples use indexing to access individual elements. Indexing starts from 0 for the first element, 1 for the second element, and so on.
  3. Heterogeneous Elements: Both lists and tuples can store elements of different data types, such as integers, floats, strings, or even other lists or tuples.
  4. Iterable: Both lists and tuples are iterable, allowing you to loop over the elements using a `for` loop or perform various operations on each element.

Examples:

# List and Tuple with similar data
my_list = [1, 2, 3, "apple", 3.14]
my_tuple = (1, 2, 3, "apple", 3.14)

# Accessing elements by index
print(my_list[1]) # Output: 2
print(my_tuple[1]) # Output: 2

# Slicing
print(my_list[1:4]) # Output: [2, 3, 'apple']
print(my_tuple[1:4]) # Output: (2, 3, 'apple')

# Iteration
for item in my_list:
print(item, end=" ") # Output: 1 2 3 apple 3.14

print() # Line break

for item in my_tuple:
print(item, end=" ") # Output: 1 2 3 apple 3.14

Python Functions

Python Function Introduction

A function in Python is a block of reusable code that performs a specific task. Functions help organize code, reduce repetition, and improve readability.

✔ Avoid repeating code
✔ Break large programs into small logical pieces
✔ Improve readability and maintainability
✔ Make code scalable and easier to debug


Syntax

Example


Output


Output


If no value is passed, default will be used.


Arguments can be passed using the parameter name.


Used when you don’t know how many arguments will be passed.


Accepts key-value pairs (dictionary-like).


Short, one-line functions without a name.


Function inside another function.




Best Practices

PracticeDescription
Use meaningful namescalculate_total() is better than ct()
Keep functions shortOne task per function
Document your functionWrite comments or use docstrings
Avoid global variablesPrefer passing parameters

Python Dictionary

Python Dictionary Introduction

Python dictionaries are a built-in data type used to store key-value pairs. They are mutable and allow for efficient retrieval and manipulation of data. Dictionaries are defined using curly braces ({}) and contain comma-separated key-value pairs. Here’s an example:

In this example, “name”, “age”, and “occupation” are the keys, and “Yash”, 23, and “Architect” are the corresponding values. The keys must be unique within a dictionary, but the values can be of any data type.

You can access the values in a dictionary by using the corresponding key:

  1. Key-Value Pairs: Python dictionaries are a collection of key-value pairs, where each key is unique and associated with a value.
  2. Mutable: Dictionaries are mutable, which means you can modify, add, or remove key-value pairs after the dictionary is created.
  3. Dynamic Sizing: Dictionaries in Python can dynamically resize to accommodate an arbitrary number of key-value pairs.
  4. Unordered: Dictionaries are unordered, meaning the items are not stored in any particular order.
  5. Efficient Data Retrieval: Dictionaries provide fast and efficient data retrieval based on the key.
  6. Various Data Types: Python dictionaries can store values of any data type, including integers, floats, strings, lists, tuples, other dictionaries, and even custom objects. This flexibility allows you to organize and structure data in a way that suits your specific needs.
  7. Membership Testing: Dictionaries provide efficient membership testing using the `in` operator. You can check if a key exists in a dictionary without iterating over all the items, making it convenient for conditional operations.
  8. Uniqueness of Keys: Python dictionary keys must be unique. This property ensures that each key is associated with a single value, preventing duplicate entries

  1. `len()` function: Returns the number of key-value pairs in a dictionary.
  1. `keys()` method: Returns a view object that contains all the keys in a dictionary.
  1. `values()` method: Returns a view object that contains all the values in a dictionary.
  1. `items()` method: Returns a view object that contains all the key-value pairs as tuples in a dictionary.
  1. `get()` method: Returns the value associated with a given key. It allows specifying a default value to be returned if the key is not found.
  1. `pop()` method: Removes and returns the value associated with a given key. It takes the key as an argument and removes the corresponding key-value pair from the dictionary.
  1. `update()` method: Merges the key-value pairs from another dictionary into the current dictionary. If a key already exists, the value is updated; otherwise, a new key-value pair is added.
  1. `clear()` method: Removes all key-value pairs from a dictionary, making it empty.

  1. Membership Operators:

   – `in` operator: Returns `True` if a key exists in the dictionary, otherwise `False`.

   – `not in` operator: Returns `True` if a key does not exist in the dictionary, otherwise `False`.

  1. Comparison Operators:

   – `==` operator: Returns `True` if two dictionaries have the same key-value pairs, otherwise `False`.

   – `!=` operator: Returns `True` if two dictionaries have different key-value pairs, otherwise `False`.

  1. Assignment Operator:

   – `=` operator: Assigns a dictionary to a variable.

  1. Deletion Operator:

   – `del` operator: Deletes an entire dictionary or a specific key-value pair.

Python Set

Python Set Introduction:

In Python, a set is an unordered collection of unique elements. Sets are mutable and can be modified using various methods.

To create a set in Python, you can use curly braces `{}` or the built-in `set()` function. Here’s an example.

  1. Uniqueness: Sets are collections of unique elements. Each element appears only once in a set. If you try to add a duplicate element, it will be ignored.
  2. Mutable: Sets are mutable, meaning you can modify them by adding or removing elements after they are created.
  3. Unordered: Sets are unordered collections, which means the elements are not stored in any particular order. You cannot access elements by indexing or slicing.
  4. Creation: Sets can be created using curly braces `{}` or the built-in `set()` function. For example.

5. Membership Testing: Sets provide an efficient way to test if an element exists in a set using the `in` operator. This operation has a constant-time complexity compared to lists or tuples.

6. Iteration: You can iterate over the elements of a set using a `for` loop, which will visit each element in an arbitrary order.


In Python, you can delete a set using the `del` keyword. Here’s an example of how to delete a set. Here’s an example:

In the example above, the `del` keyword is used to delete the `my_set` variable, which contains the set. After deleting the set, any attempt to access or use the set will result in a `NameError` because the set no longer exists.


  1. Union: The union of two sets `A` and `B` contains all unique elements from both sets. In Python, you can perform the union operation using the `union()` method or the `|` operator.
  1. Intersection: The intersection of two sets `A` and `B` contains only the elements that are common to both sets. In Python, you can perform the intersection operation using the `intersection()` method or the `&` operator.
  1. Difference: The difference between two sets `A` and `B` contains the elements that are in `A` but not in `B`. In Python, you can perform the difference operation using the `difference()` method or the `-` operator.
  1. Symmetric Difference: The symmetric difference of two sets `A` and `B` contains the elements that are in either `A` or `B`, but not both. In Python, you can perform the symmetric difference operation using the `symmetric_difference()` method or the `^` operator.
  1. len(): The `len()` function returns the number of elements in a set.
  1. add(): The `add()` method adds an element to a set.
  1. remove(): The `remove()` method removes an element from a set. It raises a KeyError if the element does not exist in the set.
  1. discard(): The `discard()` method removes an element from a set if it exists. It does not raise an error if the element is not found.
  1. pop(): The `pop()` method removes and returns an arbitrary element from the set. Since sets are unordered, the popped element is not guaranteed to be the first or last element.
  1. clear(): The `clear()`method removes all elements from a set, making it empty.
  1. copy(): The `copy()` method creates a shallow copy of a set, allowing you to work with a separate copy of the original set.