If you are a developer or what to learn python to kick start you programming career then read this article.
DSA which is known as a short from for data structure and algorithm serve as the backbone for efficient problem-solving and software development.
As, It will help you to understand how Python is known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts.
In this article you will understand data structure and algorithm, covering arrays, linked lists, queues, hash maps, heaps, trees, and specialized algorithms like Bisect, Interval Trees, and Trie Trees.
Let’s get started –
Library Used to Implement Array in Python
‘Array’ library is used to implement an array in python. In simple terms and array is collection of data which can be character,string,numbers.
Important Methods in Array library
- array.itemsize()
- array.buffer_info()
- array.count(x)
- array.extend(iterable)
Syntax to use Array Library in Python –
import array
# Create an array
array_name = array.array('typecode', [element1, element2, ...])
Example which demonstrates the use of array library in Python
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5])
# Access elements of the array
print("First element:", arr[0])
print("Second element:", arr[1])
# Append elements to the array
arr.append(6)
print("Appended array:", arr)
# Remove elements from the array
arr.remove(3)
print("Array after removing element 3:", arr)
# Find the index of an element
index = arr.index(4)
print("Index of element 4:", index)
# Get the length of the array
length = len(arr)
print("Length of the array:", length)
Output:

The typecode in the array creation specifies the type of elements in the array. Here are some common typecodes:
'i': signed integer'f': floating point'd': double precision floating point'b': signed integer (char)'u': unicode character
Explanation of the above code:
import array: This line tells Python to import thearraymodule, which allows us to work with arrays.arr = array.array('i', [1, 2, 3, 4, 5]): This line creates an array namedarrcontaining integers. The'i'in thearray.arrayfunction specifies that the array will contain integers. The second argument[1, 2, 3, 4, 5]is a list of integers that initialize the array.print("First element:", arr[0]): This line prints the first element of the arrayarr. Array elements are accessed using square brackets[ ], with the index of the element inside the brackets. In this case,arr[0]accesses the first element.print("Second element:", arr[1]): This line prints the second element of the arrayarr. Array indexing in Python starts from 0, soarr[1]accesses the second element.arr.append(6): This line appends the integer6to the end of the arrayarr. Theappendmethod adds a new element to the array.print("Appended array:", arr): This line prints the entire arrayarrafter appending6to it. This allows us to see the updated array.arr.remove(3): This line removes the integer3from the arrayarr. Theremovemethod removes the first occurrence of the specified value from the array.print("Array after removing element 3:", arr): This line prints the entire arrayarrafter removing3from it. This allows us to see the updated array.index = arr.index(4): This line finds the index of the integer4in the arrayarrand stores it in the variableindex. Theindexmethod returns the index of the first occurrence of the specified value in the array.print("Index of element 4:", index): This line prints the index of the integer4in the arrayarr.length = len(arr): This line calculates the length of the arrayarr(i.e., the number of elements in the array) and stores it in the variablelength. Thelenfunction returns the length of the array.print("Length of the array:", length): This line prints the length of the arrayarr, which indicates how many elements are in the array.
Library to Implement Linked list in Python
LinkedList can be implemented with the help of classes
The syntax for implementing a linked list in Python involves defining two classes: Node and LinkedList.
Node class: Represents an individual element of the linked list.
class Node:
def __init__(self, data):
self.data = data
self.next = None
LinkedList class: Represents the linked list and contains methods to perform operations on the linked list.
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
# Insert a new node at the beginning of the linked list
...
def insert_at_end(self, data):
# Insert a new node at the end of the linked list
...
def print_list(self):
# Print the contents of the linked list
...
To use the linked list, you would create an instance of the LinkedList class and then use its methods to insert nodes and print the list.
Example to implement LinkedList in Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_at_end(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def print_list(self):
current_node = self.head
while current_node:
print(current_node.data, end=" ")
current_node = current_node.next
print()
# Create a new linked list
llist = LinkedList()
# Insert some nodes
llist.insert_at_end(1)
llist.insert_at_end(2)
llist.insert_at_end(3)
llist.insert_at_beginning(0)
# Print the linked list
llist.print_list()
Explain each line of code above:
class Node:: This defines a class namedNode, which represents a single element in a linked list.def __init__(self, data):: This is a special method called the constructor, which initializes a newNodeobject with the givendatavalue.self.data = data: This line sets thedataattribute of theNodeobject to the provideddatavalue.self.next = None: This line sets thenextattribute of theNodeobject toNone, indicating that it is initially not connected to any other node.class LinkedList:: This defines a class namedLinkedList, which represents the entire linked list.def __init__(self):: This is the constructor for theLinkedListclass, which initializes a new linked list with no nodes.self.head = None: This line sets theheadattribute of theLinkedListobject toNone, indicating that the list is initially empty.def insert_at_beginning(self, data):: This method inserts a new node with the provideddatavalue at the beginning of the linked list.new_node = Node(data): This line creates a newNodeobject with the givendatavalue.new_node.next = self.head: This line sets thenextattribute of the new node to the current head of the linked list.self.head = new_node: This line updates theheadattribute of the linked list to point to the new node, effectively inserting it at the beginning.def insert_at_end(self, data):: This method inserts a new node with the provideddatavalue at the end of the linked list.new_node = Node(data): This line creates a newNodeobject with the givendatavalue.if self.head is None:: This condition checks if the linked list is empty (i.e.,headisNone).self.head = new_node: If the list is empty, this line sets theheadattribute to the new node, effectively making it the only node in the list.last_node = self.head: This line initializes a variablelast_nodeto theheadof the linked list.while last_node.next:: This loop iterates through the linked list until it reaches the last node (i.e., the node whosenextattribute isNone).last_node = last_node.next: This line moveslast_nodeto the next node in the list.last_node.next = new_node: Once the last node is found, this line sets itsnextattribute to the new node, effectively inserting it at the end.def print_list(self):: This method prints all the elements of the linked list.current_node = self.head: This line initializes a variablecurrent_nodeto theheadof the linked list.while current_node:: This loop iterates through the linked list until it reaches the end (i.e.,current_nodebecomesNone).print(current_node.data, end=" "): This line prints thedataattribute of the current node.current_node = current_node.next: This line movescurrent_nodeto the next node in the list.print(): This line prints a newline character to move to the next line after printing all the elements of the linked list.llist = LinkedList(): This line creates a new instance of theLinkedListclass, representing a new empty linked list.llist.insert_at_end(1),llist.insert_at_end(2),llist.insert_at_end(3),llist.insert_at_beginning(0): These lines insert nodes with values1,2,3, and0at the end and beginning of the linked list, respectively.llist.print_list(): This line prints all the elements of the linked list, resulting in the output0 1 2 3in this case.
Library to Implement Queue in Python
The ‘queue.Queue library’ in Python is used to implement Queue in Python.
Important Methods which can he helpful –
- Queue.qsize(): Return the approximate size of the queue.
- Queue.empty(): Return True if the queue is empty, False otherwise.
- Queue.full(): Return True if the queue is full, False otherwise.
- Queue.put(): Put item into the queue.
- Queue.get(): Remove and return an item from the queue.
Example:
from queue import Queue
# Creating a queue
my_queue = Queue()
# Adding elements to the queue
my_queue.put(1)
my_queue.put(2)
my_queue.put(3)
# Removing elements from the queue
# Removes and returns the first element added (FIFO)
element = my_queue.get()
print(element)
# Checking if the queue is empty
print(my_queue.empty())
# Getting the size of the queue
print(my_queue.qsize())
# Other methods available in Queue include: empty,
# qsize, full, task_done, join, etc.

Explanation of the above code:
class Queue:: This line defines a new class namedQueue, which will represent our queue data structure.def __init__(self):: This is the constructor method for theQueueclass. It initializes a new queue with an empty list of items.self.items = []: This line creates an empty list calleditemsto store the elements of the queue.def enqueue(self, item):: This method adds a new item to the end of the queue. It takes an argumentitemwhich is the value to be added to the queue.self.items.append(item): This line appends theitemto the end of theitemslist, effectively adding it to the queue.def dequeue(self):: This method removes and returns the item at the front of the queue.if not self.is_empty():: This line checks if the queue is not empty before dequeuing. If the queue is empty, it raises anIndexError.return self.items.pop(0): This line removes and returns the item at index0(the front of the queue) using thepopmethod.else: raise IndexError("Queue is empty"): If the queue is empty, this line raises anIndexErrorwith the message “Queue is empty”.def is_empty(self):: This method checks if the queue is empty. It returnsTrueif the queue is empty andFalseotherwise.return len(self.items) == 0: This line uses thelenfunction to check if the length of theitemslist is0, indicating an empty queue.def size(self):: This method returns the number of items in the queue.return len(self.items): This line returns the length of theitemslist, which represents the number of items in the queue.q = Queue(): This line creates a new instance of theQueueclass, which initializes an empty queue.q.enqueue(1),q.enqueue(2),q.enqueue(3): These lines enqueue three items (1, 2, and 3) into the queueq.print("Queue size:", q.size()): This line prints the size of the queue using thesizemethod.print("Dequeued item:", q.dequeue()),print("Dequeued item:", q.dequeue()): These lines dequeue two items from the queueqand print them.print("Queue size after dequeuing:", q.size()): This line prints the size of the queue after dequeuing two items.
Which Library is used to implement Hash Map in Python ?
The ‘collections.Counter library’ in Python is used to implement Hash Map in Python.
the collections.Counter library in Python is like a special tool that helps you create and work with hash maps, which are data structures that store key-value pairs. This library makes it easy to count and manipulate the frequency of items in a collection, like a list or a string.
Example:
from collections import Counter
# Create a Counter object from a list
my_list = ['apple', 'banana', 'apple', 'orange', 'apple', 'banana']
my_counter = Counter(my_list)
print(my_counter)
Output:

Explanation of the above code:
In the above code, we’re using the Counter class from the collections module in Python to create a frequency counter for the items in the my_list list. The Counter class automatically counts the frequency of each item in the list and stores it as key-value pairs, where the key is the item and the value is its frequency. When we print my_counter, we’ll see a dictionary-like output showing the frequency of each item in the list.
Library for Maintaining dictionaries in Python ?
The most efficient library for maintaining dictionaries in python is ‘Chainmap‘ let us see an example below to understand what exactly it is and how does it works –
# Python program to demonstrate ChainMap
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
# Defining the chainmap
c = ChainMap(d1, d2, d3)
Output:

apart from the above library we also have a library which is known as ‘OrderedDict Library’. Now, how exactly this works ?
The OrderedDict is a dictionary subclass provided by the collections module in Python. It’s similar to the built-in dict class but with one key difference: it maintains the order of insertion of its keys.
from collections import OrderedDict
my_ordered_dict = OrderedDict()
Library to Implement Bisect Algorithm in Python
‘intervaltree library’ in Python is used to implement Queue in Python.
Important Methods in intervaltree library
The intervaltree module in Python provides several methods for efficiently working with interval trees.
- add(interval): Adds an interval to the interval tree.
- remove(interval): Removes an interval from the interval tree.
- search(begin): Searches for intervals that overlap with the given range defined by begin and end (inclusive).
- overlap(begin): Alias for search(). Searches for intervals that overlap with the given range defined by begin and end.
- at(begin): Searches for intervals that contain the specified point begin. Returns a set of intervals that contain the point.
- clear(): Clears all intervals from the interval tree, making it empty.
- copy(): Creates a shallow copy of the interval tree, including all intervals.
- discard(interval): Removes an interval from the interval tree if it exists, similar to the remove() method.
- items(): Returns a generator that yields all intervals stored in the interval tree.
- size(): Returns the number of intervals stored in the interval tree.
- empty(): Returns True if the interval tree is empty, False otherwise.
Example:
from intervaltree import IntervalTree, Interval
# Create an interval tree
tree = IntervalTree()
# Add intervals to the tree
tree.add(Interval(1, 5))
tree.add(Interval(3, 8))
tree.add(Interval(6, 10))
tree.add(Interval(12, 15))
# Query intervals that overlap with a given range
query_range = (4, 7)
result_intervals = tree.search(*query_range)
print("Intervals that overlap with the query range:", result_intervals)
# Iterate over the result intervals and print their start and end points
print("Start and end points of the overlapping intervals:")
for interval in result_intervals:
print("Start:", interval.begin, "End:", interval.end)
Explanation of the above code:
from intervaltree import IntervalTree, Interval: This line imports theIntervalTreeandIntervalclasses from theintervaltreemodule. These classes are used to work with interval trees in Python.tree = IntervalTree(): This line creates an empty interval tree namedtree.tree.add(Interval(1, 5)),tree.add(Interval(3, 8)), etc.: These lines add intervals to thetree. EachIntervalobject represents a range of values, defined by its start and end points.query_range = (4, 7): This line defines a query range as a tuple with start point 4 and end point 7.result_intervals = tree.search(*query_range): This line searches thetreefor intervals that overlap with thequery_range. The*operator unpacks thequery_rangetuple into separate arguments for thesearchmethod.print("Intervals that overlap with the query range:", result_intervals): This line prints the intervals that overlap with thequery_range.for interval in result_intervals:: This line starts a loop that iterates over each interval inresult_intervals.print("Start:", interval.begin, "End:", interval.end): This line prints the start and end points of each overlapping interval inresult_intervals.





Leave a Reply