Data structures refer to a way of organizing and storing data in a computer so
that it can be accessed and used efficiently.
Essentially, a data structure is a collection of data values, the relationships
among them, and the operations that can be performed on them.
Some common examples of data structures include
o Arrays
o Linked List
o Stack
o Queue
o Trees and Graphs
Each data structure has its own unique set of operations and use cases.
ARRAYS
import array
Arrays are a simple data structure # create an array of integers
that stores a collection of elements
arr = array.array('i', [1, 2, 3, 4, 5])
of the same type in contiguous
memory locations. This allows for # access elements of the array
efficient random access to print(arr[0]) # prints 1
individual elements. print(arr[3]) # prints 4
# insert an element into the array
An array is a collection of elements
of the same type stored in arr.insert(2, 6)
contiguous memory locations. In print(arr)
Python, arrays are implemented # prints array('i', [1, 2, 6, 3, 4, 5])
using the built-in "array" module.
, class Node: LINKED LIST
def __init__(self, data):
Linked lists are a more flexible data
self.data = data structure that allows for efficient
self.next = None insertion and deletion of elements, but
class LinkedList: may not allow for efficient random
access.
def __init__self):
self.head = None A linked list is a collection of elements
def add(self, data): where each element contains a
new_node = Node(data)
reference to the next element in the
list. In Python, linked lists can be
new_node.next = self.head
implemented using classes and objects.
self.head = new_node
def print_list(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
# create a linked list and add some elements
ll = LinkedList()
ll.add(1)
ll.add(2)
ll.add(3)
# print the contents of the linked list
ll.print_list() # prints 3, 2, 1