Data Structures and Algorithms in Python

This lesson serves as a simple introduction to Python's data structures and algorithms. With the aid of practical and thoroughly explained illustrations, we will go over the built-in data structures like lists, sets, dictionaries, tuples, etc., as well as a few other user-defined data structures like linked trees, lists, and graphs, as well as some commonly used algorithms.

Lists

Likewise, arrays in other computer languages and lists in Python are collections of items arranged in any manner. It permits many data types of elements in the list. Python's version of lists is comparable to C++'s vectors or Java's array lists. As all the components must be relocated, adding or removing a member from the list's head is the most expensive operation. If the pre-allocated memory is all used up, insertion and deletion of an element at the end of the list may also become costly.

Code

Output

The created Python list is: 
['Python', 'Data', 'Structures', 'Tutorial']
The multi-Dimensional list is: 
[['Python', 'Data'], ['Structures', 'Tutorial']]
Single element:  Data
Multiple elements (slicing):  ['Python', 'Data']
For nested lists:  Structures
Last element:  ['Structures', 'Tutorial']
Last two elements:  ['Tutorial', 'Structures']

Tuple

Lists and Python tuples are equivalent, but unlike lists, tuples are immutable, meaning that once formed, we cannot change them. A Tuple can include components of several types, just like a List.

Python tuples are made by grouping together a series of values. These values are delimited by a "comma", regardless of whether or not the parenthesis is used.

Code

Output

The Python tuple is: 
('Python', 'Data', 'Structures', 'Tutorial')
Tuple using a List: 
Single element:  Data
Multiple elements (slicing):  ('Python', 'Data')
Last element:  Tutorial
Exception raised:  'tuple' object does not support item assignment

Set

A Python set data structure is a non-duplicate data collection that is modifiable. Sets are mainly used for membership screening and removing redundant entries. These processes use the Hashing data structure, a popular method for traversal, insertion, and deletion of elements that typically takes O(1) time.

Code

Output

The Python Set is: 
{'Python', 'Data', 'Tutorial', 'Structures'}
0 Python
1 Data
2 Tutorial
3 Structures
Intersection:  {'Python', 'Data'}
Union:  {1, 2, 'Structures', 'Python', 'Tutorial', 'Data'}

Dictionary

A key-value pair-formatted data collection called a Python dictionary is used to store data. The temporal complexity of this data structure is O(1), much like hash tables in other coding languages. The Python Dictionary is indexed with the help of the keys. The values of keys can be of any type, i.e., a constant item like a string, integer, sequence, etc. We can build a dictionary using curly brackets {} or dictionary comprehension.

Code

Output

The Python Dictionary is: 
{'1': 'Python', '2': 'Data', '3': 'Structures', '4': 'Tutorial'}
Value of key 2 is:  Data
Using the get method:  Data

Linked List

A linear data structure called a linked list has elements that are not kept in consecutive locations in memory. A linked list's elements are connected via pointers.

A pointer to the first node of the linked list serves as the representation of a linked list. The head refers to the top node. The head's value is NULL if the linked list is empty. In a list, each node has at least two components:

  • Data
  • Pointer (Or Reference) to the next node

Code

Output

Python
Tutorial
Data Structures

Linked lists are important data structures. Here are a few essential operations of the linked list.

Code

Output

Linked list:
9 4 8 7 2 
After deleting a node:
9 4 7 2 
 4 is found in the list
Sorted Linked List: 
2 4 7 9 

Stack

A stack is a linear data structure that uses either first-in and last-out (FILO) or last-in and first-out (LIFO) ordering to store objects. In a stack, an item is deleted only from one end while a new item is put to the other. Push and pop are common names for the actions of insert and deletion.

Basic Operations of Stack

We may carry out various activities on a stack using a few fundamental operations.

Push: This method adds an item to the top of the stack

Pop: This method will remove an item from the top of the stack

IsEmpty: This method checks whether the stack is empty or not.

IsFull: This method checks whether the stack is full or not.

Peek: This method will return the top element but not remove it.

Code

Output

New stack after pushing:  [2]
New stack after pushing:  [2, 5]
New stack after pushing:  [2, 5, 3]
New stack after pushing:  [2, 5, 3, 1]
New stack after popping:  [2, 5, 3]
Last element of the stack:  3

Queue

The queue, which holds objects in a First In First Out (FIFO) order, is another linear data structure similar to a stack. A queue removes items in the order that we most recently added them. Any line of users waiting to access a service where the user who arrived first is serviced first is an excellent illustration of a queue.

Operations Linked to the Queue Include:

Enqueue: Adds a piece of content to the queue. Overflow conditions are defined as when the queue is filled. The time complexity of adding an element to a queue: O(1)

Dequeue: Takes something out of the queue. The things are popped in the same sequence that the values are enqueued. It's called an underflow condition if a queue is empty. Getting the first item of the queue has an O(1) time complexity.

Rear: Obtain the last item in the queue. The time complexity to get the last item of the queue is O(1).

Code

Output

New queue after enqueuing:  [6]
New queue after enqueuing:  [6, 3]
New queue after enqueuing:  [3, 9]
Last element:  9

Heap

The heap data structure, which is mainly designed to describe a priority queue, is provided by the Python heapq module. The characteristic of the heap data structure is that anytime an item is popped, it always returns the smallest item (min-heap). Items are always pushed or popped while the heap structure is preserved. Additionally, the heap[0] item consistently returns the smallest value. It enables O(log n)-time retrieval and insertion of the lowest value element.

Heaps often come in two varieties:

Max-Heap: Max-Heap data structure's root node's key must rank highest amongst its child's keys. The same condition should be recursively true for every sub-tree in a Binary Tree.

Min-Heap: Min-Heap's root node's key should be the least common key of all of its child's keys. The same condition should be recursively true for every sub-tree in a Binary Tree.

Code

Output

Heap array:  [6, 4, 5, 3, 8]
After deleting an item:  [8, 4, 6, 3]

Binary Tree

A nonlinear hierarchy data structure called a tree comprises nodes and edges.

A Python tree data structure known as a binary tree allows each parent node to have a maximum of two children. A binary tree has three components at each node:

  1. A data element
  2. An address of the left child
  3. An address of the right child

Code

Output

Pre-order traversal of the tree: 4 5 10 1 0 7 2 9 
In-order traversal of the tree: 10 1 5 0 4 2 9 7 
Post-order traversal of the tree: 1 10 0 5 9 2 7 4 

Bubble Sort Algorithm

A sorting method known as bubble sort analyses two nearby items and swaps those until the desired order is achieved.

Each item of the list moves to the end of the list in each iteration. This is similar to the behaviour of the air bubbles in the liquid that come to the surface. Consequently, it is known as a bubble sort.

Code

Output

Sorted List in Descending Order:
[9, 7, 5, 3, 2, 0] 

Selection Sort Algorithm

A sorting algorithm known as selection sort chooses the maximum element of an unsorted list for every iteration and inserts it at the start of the list.

Code

Output

Sorted List in Descending Order:
[97, 85, 35, 29, 23, 20]

Quicksort Algorithm

An array is split into smaller arrays using the divide-and-conquer strategy in the sorting algorithm known as Quicksort (item taken from the array).

When splitting the given array, the pivot component should be set so that items of value greater than the pivot component are located on the right side, and components with a value less than the pivot value are stored on the left side.

The same method is used to divide the right and left subarrays. This procedure is repeated until only one element remains in each subarray.

The elements have already been sorted at this point. The combination of the items creates a sorted array at the end.

Code

Output

Sorted List in Ascending Order:
[0, 1, 2, 3, 4, 7, 8, 9]

Counting Sort Algorithm

A sorting method known as counting sort arranges the given array of elements according to the number of times every distinct element appears in the given array. Sorting is done by mapping the count of the elements of the array as an index of another array made by us. This array stores the count of elements.

Code

Output

Sorted list: 
[2, 2, 3, 4, 7, 7, 8, 9]

Binary Search Algorithm

Binary Search is a searching algorithm for finding an element's position in a sorted array.

In this approach, the element is always searched in the middle of a portion of an array.

Code

Output

The element we searched for is present at: 4





Latest Courses