Unit-1 Basics of Object Oriented Programming
Unit-1 Basics of Object Oriented Programming
(A.I.O.P.D.)
Class
A class is a collection of objects.
A class is a blueprint for creating objects.
It defines attributes (variables) and methods (functions).
Part Meaning
def Define a method
__init__ Constructor method
self Refers to the current object
self.name = name Stores the name in the object
self.age = age Stores the age in the object
Example:
class Student:
self.name = name
Note: The __init_() function is called automatically every time the class is being used to create a
new object.
Note: The self parameter is a reference to the current instance of the class, and is used to access
variables that belong to the class.
Object
An object is an instance of a class.
It has real values assigned to class properties.
Example:
s1 = Student("Alice")
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
Example:
class Student:
def __init__(self, a, b):
self.name = a
self.rollno = b
def myfunc(self):
print("Hello my name is " + self.name)
s1 = Student("John", 36)
s1.myfunc()
Or
class Student:
def __init__(obj, name, rollno):
obj.name = name
obj.rollno = rollno
def myfunc(abc):
print("Hello my name is " + abc.name)
Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It
describes the bundling of data (attributes) and methods that operate on that data into a single
unit, usually a class. It also refers to restricting access to some of an object's components, which
helps prevent the accidental modification of data.
Key Features of Encapsulation in Python
1. Private and Protected Members:
o Public members: Accessible from anywhere (self.name)
o Protected members: Indicated by a single underscore (_name). Treated as
internal use only.
o Private members: Indicated by a double underscore (__name). Name mangled to
prevent access from outside the class directly.
2. Getter and Setter Methods:
o Used to read and update private attributes safely.
Note: private data members are only accessed within the class
class encapsul:
_a=10 # protected member
__b=20 # private member
def show(self):
print("protected a = ",self._a)
print("private b = ",self.__b)
e=encapsul()
e.show()
print("outside of class protected member",e._a)
#print("outside of class private member",e.__b)
print("access -> outside of class private member",encapsul._encapsul__b)
Output:
protected a = 10
private b = 20
outside of class protected member 10
outside of class private member 20
Change -> outside of class private member 50
Encapsulation
Encapsulation in Python is a fundamental concept in object-oriented programming (OOP) that
involves bundling data (attributes) and methods (functions) that operate on that data within a
single unit, which is a class.
Example of Encapsulation:
class Student:
def __init__(self, name, age, grade):
self.name = name # Public attribute
self._age = age # Protected attribute
self.__grade = grade # Private attribute
output:
Public (Name): John Doe
Protected (Age): 18
Private (Grade): 85
Updated Grade: 92
Invalid grade. Must be between 0 and 100.
Output:
Full Student Info:
Name: John Doe
Age: 18
Grade: 92
Access specifiers in Python have an important role to play in securing data from unauthorized
access and in preventing it from being exploited.
A constructor is a special method used to initialize objects when they are created from a
class. It is automatically invoked when a new instance of a class is created. The primary
purpose of a constructor is to set up the initial state of the object by assigning values to its
attributes or performing any necessary setup operations.
class stud:
def __init__(a, name,rno):
a.name=name
a.rno=rno
s1=stud("abc",25)
print(s1.name)
print(s1.rno)
Output:
abc
25
def __del__(self):
print(f"Object {self.name} is being destroyed")
# Example usage
obj = MyClass("Test")
del obj # Manually deletes the object, triggers __del__()
Output:
Object Test created
Object Test is being destroyed
Inheritance:
Inheritance comes into picture when a new class possesses 'IS A' relationship with an existing
class. For example, Car IS a vehicle, Bus IS a vehicle, Bike IS also a vehicle. Here, Vehicle is
the parent class, whereas car, bus and bike are the child classes.
1. Parent Class:
This is the base class from which other classes inherit.
It contains attributes and methods that the child class can reuse.
2. Child Class:
This is the derived class that inherits from the parent class.
The syntax for inheritance is class ChildClass (ParentClass).
The child class automatically gets all attributes and methods of the parent class unless
overridden.
Syntax for Inheriting child class: class ChildClass(ParentClass):
class ChildClass(ParentClass):
# Child class code here
For example, if you have a parent class called Animal, a child class like Dog can inherit from it
and get all the basic features of an animal, like eating or sleeping. Then you can add special
features just for dogs.
Single Inheritance
This type of inheritance where a child class (also known as a derived class or subclass) inherits
attributes and methods from only one parent class (also known as a base class)
Example 1:
# parent class
class Parent:
def parentMethod(self):
print ("Calling parent method")
# child class
class Child(Parent):
def childMethod(self):
print ("Calling child method")
# instance of child
c = Child()
# calling method of child class
c.childMethod()
# calling method of parent class
c.parentMethod()
Output:
Calling child method
Calling parent method
Example 2:
# A Python program to demonstrate Single inheritance
#Base Class
class Person():
# Constructor
def __init__(self, name, id):
self.name = name
self.id = id
#Derived Class
class Emp(Person):
def Print(self):
print("Emp class called")
print(self.name, self.id)
#Creae Object
Emp_details = Emp("ABC", 101)
# calling parent class function
print("Call base class method - Display")
Emp_details.Display()
Output:
Call base class method - Display
Parent Class method
ABC 101
Call Derived class method - print
Emp class called
ABC 101
Multiple Inheritance
In this inheritance a class can inherit attributes and methods from more than one parent
class. This allows a child class to combine functionalities from multiple sources
super() Function
class Parent:
def show(self):
print("This is the parent class.")
class Child(Parent):
def show(self):
super().show() # Calls Parent's show()
print("This is the child class.")
c = Child()
c.show()
Output:
This is the parent class.
This is the child class.
# Parent class 2
class StudentDetails:
def display_student_info(self):
print(f"Student ID: {self.student_id}, Course: {self.course}")
# Child class inheriting from both Person and StudentDetails
class Student(Person, StudentDetails):
def set_details(self):
self.name = input("Enter name: ")
self.age = int(input("Enter age: "))
self.student_id = input("Enter student ID: ")
self.course = input("Enter course: ")
def display(self):
self.display_person_info()
self.display_student_info()
Output:
Enter name: Pooja
Enter age: 25
Enter student ID: 101
Enter course: BCA
Name: Pooja, Age: 25
Student ID: 101, Course: BCA
def display_student_info(self):
print(f"Name: {self.name}")
print(f"Roll Number: {self.roll_no}")
# Derived Class 1
class AcademicStudent(Student):
def __init__(self, name, roll_no, marks):
super().__init__(name, roll_no)
self.marks = marks
def display_academic_info(self):
self.display_student_info()
print(f"Academic Marks: {self.marks}")
# Derived Class 2
class SportsStudent(Student):
def __init__(self, name, roll_no, sport):
super().__init__(name, roll_no)
self.sport = sport
def display_sports_info(self):
self.display_student_info()
print(f"Sport: {self.sport}")
Output:
=== Academic Student ===
Name: ABC
Roll Number: 15
Academic Marks: 50
A class is derived from another derived class (Intermediate base class) that is Multilevel
inheritance.
For example:
Base -> Derived1 -> Derived2
# Derived Class 1
class AcademicStudent(Student):
def __init__(self, name, roll_no, subject):
super().__init__(name, roll_no)
self.subject = subject
def display_academic_info(self):
print(f"Subject: {self.subject}")
def display_result(self):
self.display_student_info()
self.display_academic_info()
print(f"Marks: {self.marks}")
Output:
=== Student Result ===
Name: ABC
Roll Number: S001
Subject: Mathematics
Marks: 88
Hybrid Inheritance:
Hybrid inheritance is a combination of more than one type of inheritance. For example, it can
include a mix of multiple and hierarchical inheritance.
# Base class
class Person:
def __init__(self, name):
self.name = name
def display_name(self):
print("Name:", self.name)
# Derived class 1 (single inheritance)
class Student(Person):
def __init__(self, name, student_id):
super().__init__(name)
self.student_id = student_id
def display_student_id(self):
print("Student ID:", self.student_id)
def display_marks(self):
print("Marks:", self.marks)
def display_sport(self):
print("Sport:", self.sport_name)
def display_result(self):
self.display_name()
self.display_student_id()
self.display_marks()
self.display_sport()
# Create object
r1 = Result("Alice", "S101", 88, "Basketball")
r1.display_result()
Output:
Name: Alice
Student ID: S101
Marks: 88
Sport: Basketball
Polymorphism
The word "polymorphism" means "many forms", and in programming it refers to
methods/functions/operators with the same name that can be executed on many objects or
classes.
Types of Polymorphism
Note: Python does not support true method overloading like Java or C++. The last defined
method with the same name will override the previous ones.
Example 1:
class Cat:
def sound(self):
return "Meow"
class Dog:
def sound(self):
return "Woof"
# Polymorphic function
def make_sound(animal):
print(animal.sound())
c = Cat()
d = Dog()
make_sound(c) # Meow
make_sound(d) # Woof
Output:
Meow
Woof
OR
#Polymorphism with Class Methods
class Student:
def info(self):
print("I am a student.")
class Teacher:
def info(self):
print("I am a teacher.")
Output:
I am a student.
I am a teacher.
Example 2:
class Student:
def show_info(self):
name = "ABC"
grade = "N/A"
print( f"Name: {name}, Grade: {grade}")
class ScienceStudent:
def show_info(self):
name = "PQR"
grade = "A"
print(f"Name: {name}, Grade: {grade}")
class CommerceStudent:
def show_info(self):
name = "XYZ"
grade = "B"
print(f"Name: {name}, Grade: {grade}")
# Polymorphism in action
def print_student_details(student):
student.show_info()
# Objects
s1 = Student()
s2 = ScienceStudent()
s3 = CommerceStudent()
Output:
Name: ABC, Grade: N/A
Name: PQR, Grade: A
Name: XYZ, Grade: B
Operator Overloading:
Operator overloading allows custom behavior for standard operators (like `+`, `-`, `*`, etc.) when
used with user-defined objects (like classes).
Python uses special methods (also called magic methods) to handle operator overloading.
These methods start and end with double underscores: `__add__`, `__sub__`, `__mul__`, etc.
+ __add__ a+b
- __sub__ a-b
* __mul__ a*b
/ __truediv__ a/b
== __eq__ a==b
< __lt__ a<b
Str() __str__() Str(a)
Output:
Total marks of both students: 170
Output:
Total marks: 175
Full name: ABC XYZ
Updated marks: 90.5
Explanation:
isinstance() is a built-in Python function used to check the type of a variable or object at runtime.
isinstance(object, class_or_tuple)
object: The variable you want to check.
class_or_tuple: The type (or tuple of types) you want to check against.
isinstance()-
You use it to safely perform operations based on an object’s type.
This is especially useful when overloading operators or writing functions that behave differently
based on input types.
NotImplemented → tells Python this operation isn’t supported for other types.
Output:
True
False
Output:
Difference in marks: 15
Method overriding means redefining a method in a subclass that already exists in the parent
class.
The child class provides a specific implementation of a method that is already defined in its
parent class.
Key Differences Method Overloading and Method Overriding:
Feature Method Overloading Method Overriding
Definition Same method name, different parameters Redefining a method in child class
Scope Same class Parent and child classes
Python Support Not directly supported Fully supported
Flexibility Simulated using default/variable arguments Done by redefining the method
Purpose Code flexibility in method calls Customizing inherited behavior
# Subclass 1
class Undergraduate(Student):
def get_details(self):
print("Undergraduate student: Enrolled in bachelor's program.")
# Subclass 2
class Graduate(Student):
def get_details(self):
print("Graduate student: Working on master's")
Output:
Undergraduate student: Enrolled in bachelor's program.
Graduate student: Working on master's
def get_details(self):
return f"Name: {self.name}, ID: {self.student_id}"
# Derived class 1
class UndergraduateStudent(Student):
def __init__(self, name, student_id, major):
super().__init__(name, student_id)
self.major = major
# Derived class 2
class GraduateStudent(Student):
def __init__(self, name, student_id, thesis_topic):
super().__init__(name, student_id)
self.thesis_topic = thesis_topic
# Polymorphic function
def print_student_info(student):
print(student.get_details())
# Demonstrating Polymorphism
print_student_info(student1)
print_student_info(student2)
Output:
Undergraduate Student: ABC, ID: UG123, Major: Computer Science
Graduate Student: PQR, ID: GR456, Thesis: Artificial Intelligence
A data structure is a way of organizing, managing, and storing data so that it can be accessed and
modified efficiently.
Data Structures are a way of organizing data so that it can be accessed more efficiently
depending upon the situation
Python provides several built-in data structures that are widely used for solving real-world
problems.
Built-in Data Structures in Python that mansion in syllabus is lists, sets, tuples, dictionaries.
List
Python Lists are just like the arrays, declared in other languages which is an ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.
The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The
costly operation is inserting or deleting the element from the beginning of the List as all the
elements are needed to be shifted. Insertion and deletion at the end of the list can also become
costly in the case where the pre allocated memory becomes full.
Note: A Python list is mutable. Any item from the list can be accessed using its index, and can
be modified. One or more objects from the list can be removed or added. A list may have same
item at more than one index positions.
list2 = [1, 2, 3, 4, 5]
Indexing in Lists
Positive index: Starts from 0
Negative index: Starts from -1 (last element)
print(marks[-1]) # Output: 95
Slicing Lists
Syntax: list[start:stop:step]
subjects = ["Math", "Science", "English", "History"]
print(marks_matrix[1][0]) # Output: 78
Application Areas:
# 8. List operations
new_students = ["Grace", "Hannah"]
combined = students + new_students
print("Combined List:", combined)
repeated = new_students * 2
print("Repeated List:", repeated)
# 9. Slicing
print("Sliced [1:3]:", students[1:3])
print("Every second student:", students[::2])
marks.reverse()
print("Reversed Marks:", marks)
Output:
Original Student List: ['Alice', 'Bob', 'Charlie', 'David']
First student: Alice
Last student: David
Updated Student List: ['Alice', 'Ben', 'Charlie', 'David']
After Appending 'Eve': ['Alice', 'Ben', 'Charlie', 'David', 'Eve']
After Inserting 'Liam' at index 2: ['Alice', 'Ben', 'Liam', 'Charlie', 'David', 'Eve']
After Removing 'Charlie': ['Alice', 'Ben', 'Liam', 'David', 'Eve']
After Popping Last Student: ['Alice', 'Ben', 'Liam', 'David']
Removed Student: Eve
Combined List: ['Alice', 'Ben', 'Liam', 'David', 'Grace', 'Hannah']
Repeated List: ['Grace', 'Hannah', 'Grace', 'Hannah']
Sliced [1:3]: ['Ben', 'Liam']
Every second student: ['Alice', 'Liam']
Marks List: [85, 92, 78, 95, 90]
Total Students: 4
Highest Mark: 95
Lowest Mark: 78
Marks of Liam in subject 2: 94
Sorted Marks: [78, 85, 90, 92, 95]
Reversed Marks: [95, 92, 90, 85, 78]
Count of 85 in marks: 1
Index of 90 in marks: 2
Cleared Student List: []
Backup Student List: ['Alice', 'Ben', 'Liam', 'David']
Tuple
Python Tuples are similar to lists, but they are immutable, meaning their elements cannot be
changed once assigned. Tuples are ordered collections that allow duplicate values and can store
different data types.
Creating a Tuple:
tuple1 = (10, 20, 30)
Tuple is Immutable:
tuple1[1] = 40 # ❌ Error: Tuples cannot be modified
Tuple Operations:
Operation Description Example Output
+ Concatenation (1, 2) + (3, 4) (1, 2, 3,
4)
* Repetition (1, 2) * 2 (1, 2, 1,
2)
in Membership test 3 in (1, 2, 3) True
len() Length of tuple len(tuple1) 3
min() Minimum element (comparable types only) min((4, 2, 7)) 2
Max() Maximum element max((4, 2, 7)) 7
tuple() Convert to tuple tuple([1, 2, (1, 2, 3)
3])
Slicing Tuples:
tuple1 = (10, 20, 30, 40, 50)
print(nested[1]) # (3, 4)
print(nested[1][0]) #3
# Unpacking
print(name) # John
print(age) # 25
print(job) # Engineer
Tuple Methods:
Method Description Example
.count(x) Returns the count of value x t.count(2) → 2
.index(x) Returns index of first x t.index(4) → 2
t = (1, 2, 4, 2, 5)
print(t.count(2)) # Output: 2
print(t.index(4)) # Output: 2
Application Areas:
Fixed data values (e.g., coordinates, RGB color codes)
Keys in dictionaries (if tuple is immutable)
Data integrity (e.g., database rows that shouldn't be modified)
Return multiple values from a function
Output:
red
green
blue
Output:
apple
banana
mango
i=0
print(numbers[i])
i += 1//i=i+1
Output:
10
20
30
40
Output:
John is 20 years old.
Output:
0 : cat
1 : dog
2 : elephant
Comparing Tuples
# 1. Creating Tuples
tuple1 = (10, 20, 30)
tuple2 = ("Alice", "Bob", "Charlie")
tuple3 = (25.5, True, "Hello", 1+2j)
tuple4 = () # Empty tuple
tuple5 = (5,) # Single-element tuple
# 3. Tuple is Immutable
# tuple1[1] = 40 # ❌ This will raise TypeError
# 4. Tuple Operations
print((1, 2) + (3, 4)) # Output: (1, 2, 3, 4)
print((1, 2) * 2) # Output: (1, 2, 1, 2)
print(3 in (1, 2, 3)) # Output: True
print(len(tuple1)) # Output: 3
print(min((4, 2, 7))) # Output: 2
print(max((4, 2, 7))) # Output: 7
print(tuple([1, 2, 3])) # Output: (1, 2, 3)
# 5. Slicing Tuples
t = (10, 20, 30, 40, 50)
print(t[1:4]) # Output: (20, 30, 40)
print(t[:3]) # Output: (10, 20, 30)
print(t[::2]) # Output: (10, 30, 50)
# 6. Nested Tuples
nested = ((1, 2), (3, 4), (5, 6))
print(nested[1][0]) # Output: 3
# 8. Tuple Methods
t = (1, 2, 4, 2, 5)
print(t.count(2)) # Output: 2
print(t.index(4)) # Output: 2
for i in range(len(colors)):
print(colors[i])
i=0
while i < len(colors):
print(colors[i])
i += 1 #i=i+1
tup = (4, 5, 6)
print(list(tup)) # Output: [4, 5, 6]
Output:
Alice
(1+2j)
(1, 2, 3, 4)
(1, 2, 1, 2)
True
3
2
7
(1, 2, 3)
(20, 30, 40)
(10, 20, 30)
(10, 30, 50)
3
John 25 Engineer
2
2
red
green
blue
red
green
blue
red
green
blue
John is 20 years old.
Alice is 22 years old.
Bob is 19 years old.
0 : cat
1 : dog
2 : elephant
True
True
Alice
25
(1, 2, 3)
[4, 5, 6]
Python set
Python set is an unordered collection of multiple items having different datatypes. In Python,
sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not
preserved and can change.
In Python, the most basic and efficient method for creating a set is using curly braces.
Example:
set1 = {1, 2, 3, 4}
print(set1)
Python Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by a 'comma'.
Note: A Python set cannot contain mutable types such as lists or dictionaries, because they are
unhashable.
set1 = set()
print(set1)
set1 = set("ABCDEFGH")
print(set1)
In set, the order of elements is not guaranteed to be the same as the order in which they were
added. The output could vary each time we run the program. Also the duplicate items entered are
removed by itself.
Sets do not support indexing. Trying to access an element by index (set[0]) raises a TypeError.
We can add elements to the set using add(). We can remove elements from the set
using remove(). The set changes after these operations, demonstrating its mutability. However,
we cannot changes its items directly.
set1 = {3, 1, 4, 1, 5, 9, 2}
We can add items to a set using add() method and update() method. add() method can be used to
add only a single item. To add multiple items we use update() method.
Example:
# Creating a set
set1 = {1, 2, 3}
print(set1)
Explanation:
This loop will print each item in the set. Since sets are unordered, the order of items
printed is not guaranteed.
This code checks if the number 4 is in set1 and prints a corresponding message.
We can remove an element from a set in Python using several methods: remove(),
discard() and pop(). Each method works slightly differently :
Using remove() Method or discard() Method
Using pop() Method
Using clear() Method
Note: If the set is unordered then there's no such way to determine which element is popped by
using the pop() function.
set1 = {1, 2, 3, 4, 5}
val = set1.pop()
print(val)
print(set1)
intersection_update() Updates the set with the intersection of itself and another
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
Creating a Set:
fruits = {"apple", "banana", "mango"}
Accessing Elements:
Unlike lists, you cannot access set items by index (e.g., set[0] is not allowed), because sets
are unordered.
print(fruit)
Updating a Set:
Add Items:
fruits.add("orange") # Adds a single item
Adding Duplicates:
fruits.add("apple") # Will not be added again
Set Operations:
Operation Description Example Output
union() or ` ` Combines `a
elements
intersection() or & Common elements a & b {...}
difference() or - Elements in a not in b a - b {...}
symmetric_difference() or ^ Elements in either, not both a ^ b {...}
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a - b) # {1, 2}
print(a ^ b) # {1, 2, 4, 5}
Membership Test:
"apple" in fruits # True/False
Example:
# Set Demo - All Set Operations
# 9. Membership testing
print("Is 'David' in students?", "David" in students)
print("Is 'Charlie' in students?", "Charlie" in students)
Output:
Dictionaries in Python
Python dictionary is a data structure that stores the value in key: value pairs. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and
must be immutable.
Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
find values.
Output:
ABC
ABC
print(d)
Output:
{1: 'ABC', 2: 'PQR', 3: 'XYZ', 'marks': 22}
{1: 'Dictionary update', 2: 'PQR', 3: 'XYZ', 'marks': 22}
Output:
1
2
age
Sal
ABC
Job
25
15000
1 ABC
2 Job
age 25
Sal 15000
print(d)
Output:
{1: 'ABC', 2: 'PQR', 3: {'A': 'Hello', 'B': 'Hi', 'C': 'SDJ'}}
Copy method
SDJ = {
"Sub": "BCA",
"Year": "1St",
"Sem": 1
}
x=SDJ.copy()
print(x)
fromkeys() Method
Create a dictionary with 3 keys, all with the value 0:
exp = dict.fromkeys(x, y)
print(exp)
x=SDJ.get("Year")
print(x)
SDJ.items()
print(x)
DJ.keys()
print(x)
SDJ.update({"Year": "2nd"})
print(x)
SDJ.values()
print(x)
Output:
1St
dict_items([('Sub', 'BCA'), ('Year', '1St'), ('Sem', 1)])
dict_keys(['Sub', 'Year', 'Sem'])
{'Sub': 'BCA', 'Year': '2nd', 'Sem': 1}
dict_values(['BCA', '2nd', 1])
Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Difference table between Set, List, Tuple, and Dictionary in Python:
The data structure is a method of organizing and storing data and info in a way that a user can
utilize them efficiently. In computer science, the data structure is composed in a way that it
works with various algorithms. It has two broad categories:
It is a type of Data Structure where the data elements get linearly or sequentially arranged. The
elements attach themselves to their next and previous adjacents. The structure involves only a
single level- allowing a user to traverse all its components in a single run.
The linear data structure is very easy to understand and implement due to its linear arrangement,
for example, stack, array, linked list, queue, etc.
It is a form of data structure where the data elements don’t stay arranged linearly or sequentially.
Since the data structure is non-linear, it does not involve a single level. Therefore, a user can’t
traverse all of its elements in a single run.
The non-linear data structure is not very easy to implement as compared to the linear data
structure. The utilization of computer memory is more efficient in this case, for example, graphs
and trees.
Difference table between Linear Data Structure and Non-Linear Data Structure
Feature Linear Data Structure Non-Linear Data Structure
Structure Type A structure where elements are A structure where elements are
arranged in a sequence or a arranged in a hierarchical or
linear order. interconnected manner
Real-World Applications
Use Case Recommended Structure
To-do lists, sequences list
GPS coordinates, constant pairs tuple
Unique user IDs or tags set
User profiles, settings dict
Python’s built-in data structures make it simple to handle different types of data
efficiently.
Choose the right structure based on your needs:
o Use lists for ordered and mutable collections.
o Use tuples for fixed-size and immutable groupings.
o Use sets to eliminate duplicates and for fast membership checks.
o Use dictionaries for structured data and quick lookups.