Open In App

Learn DSA with Python | Python Data Structures and Algorithms

Last Updated : 08 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc. and some user-defined data structures such as linked lists, trees, graphs, etc.

1. List

List is a built-in dynamic array which can store elements of different data types. It is an ordered collection of item, that is elements are stored in the same order as they were inserted into the list. List stores references to the objects (elements) rather than storing the actual data itself.

Python List Example:

Python
a = [10, 20, "GfG", 40, True]
print(a)

Output
[10, 20, 'GfG', 40, True]
python-list

Related Posts:

Recommended DSA Problems:

To solve more DSA Problems based on List, refer Python List DSA Problems.

2. Searching Algorithms

Searching algorithms are used to locate a specific element within a data structure, such as an array, list, or tree. They are used for efficiently retrieving information in large datasets.

Related Posts:

Recommended DSA Problems:

3. Sorting Algorithms

Sorting algorithms are used to arrange the elements of a data structure, such as an array, list, or tree, in a particular order, typically in ascending or descending order. These algorithms are used for organizing data, which enables more efficient searching, merging, and other operations.

Related Posts:

Recommended DSA Problems:

4. String

String is a sequence of characters enclosed within single quotes (‘ ‘) or double quotes (” “). They are immutable, so once a string is created, it cannot be altered. Strings can contain letters, numbers, and special characters, and they support a wide range of operations such as slicing, concatenation, etc.

Note: As strings are immutable, modifying a string will result in creating a new copy.

Python String Example:

Python
s = "Hello Geeks"
print(s)

Output
Hello Geeks

Related Posts:

Recommended DSA Problems:

5. Set

Set is a built-in collection in Python that can store unique elements of different data types. It is an unordered collection, meaning the elements do not maintain any specific order as they are added. Sets do not allow duplicate elements and automatically remove duplicates.

Python Set Example:

Python
a = {10, 20, 20, "GfG", "GfG", True, True}
print(a)

Output
{'GfG', True, 10, 20}

Related Posts:

Recommended DSA Problems:

6. Dictionary

Dictionary is an mutable, unordered (after Python 3.7, dictionaries are ordered) collection of data that stores data in the form of key-value pair. It is like hash tables in any other language. Each key in a dictionary is unique and immutable, and the values associated with the keys can be of any data type, such as numbers, strings, lists, or even other dictionaries. We can create a dictionary by using curly braces ({}).

Python Dictionary Example:

Python
# Creating a Dictionary
d = {10 : "hello", 20 : "geek", "hello" : "world", 2.0 : 55}
print(d)

Output
{10: 'hello', 20: 'geek', 'hello': 'world', 2.0: 55}

Related Posts:

Recommended DSA Problems:


Python Data Structures and Algorithms

7. Recursion

Recursion is a programming technique where a function calls itself in order to solve smaller instances of the same problem. It is usually used to solve problems that can be broken down into smaller instances of the same problem.

Related Posts:

Recommended DSA Problems:

8. Stack

Stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop. In Python, we can implement Stack using List Data Structure.

Stack Example in Python:

Python
stack = []

# append() function to push element in the stack
stack.append('g')
stack.append('f')
stack.append('g')

print('Initial stack')
print(stack)

# pop() function to pop element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')
print(stack)

Output
Initial stack
['g', 'f', 'g']

Elements popped from stack:
g
f
g

Stack after elements are popped:
[]

Related Posts:

Recommended DSA Problems:

9. Queue

Queue is a data structure that follows the First-In, First-Out (FIFO) principle, meaning the first element added is the first one to be removed. The insert and delete operations are often called enqueue and dequeue.

Queue Example in Python

Python
queue = []

# Adding elements to the queue
queue.append('g')
queue.append('f')
queue.append('g')

print("Initial queue")
print(queue)

# Removing elements from the queue
print("Elements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))

print("Queue after removing elements")
print(queue)

Output
Initial queue
['g', 'f', 'g']
Elements dequeued from queue
g
f
g
Queue after removing elements
[]

Related Posts:

Recommended DSA Problems:

10. Linked List

Linked List is a linear data structure where elements, called nodes, are stored in a sequence. Each node contains two parts: the data and a reference (or link) to the next node in the sequence. The last node points to None, indicating the end of the list. Linked List allows for efficient insertions and deletions, especially when elements need to be added or removed from the beginning or middle of the list, as no shifting of elements is required.

Linked List Example in Python:

Python
# Node class
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


if __name__=='__main__':

    # Create a linked list
    # 10 -> 20 -> 30
    head = Node(10)
    head.next = Node(20)
    head.next.next = Node(30)
    
    # Print the list
    temp = head
    while temp != None:
        print(temp.data, end = " ")
        temp = temp.next

Output
10 20 30 

Related Posts:

Recommended DSA Problems:

11. Tree

Tree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Trees are used in many areas of computer science, including file systems, databases and even artificial intelligence.

Tree Example in Python:

Python
# Structure of a Binary Tree Node
class Node:
    def __init__(self, v):
        self.data = v
        self.left = None
        self.right = None
        
def printInorder(root):
    if(root == None):
        return
    printInorder(root.left)
    print(root.data, end = " ")
    printInorder(root.right)

if __name__ == '__main__':
    
    # Construct Binary Tree of 4 nodes
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    
    printInorder(root)

Output
4 2 1 3 

Related Posts:

Recommended DSA Problems:

12. Heap

Heap is a complete binary tree that satisfies the heap property. It can be used to implement a priority queue. A max heap is a complete binary tree where the value of each node is greater than or equal to the values of its children, and the min heap is where the value of each node is less than or equal to the values of its children.

 Heap Example in Python:

Python
import heapq

a = [5, 7, 9, 1, 3]

# using heapify to convert list into heap
heapq.heapify(a)

# printing created heap
print ("The created heap is:", a)

# Push 4 into the heap
heapq.heappush(a, 4)

# printing modified heap
print ("The modified heap after push is:", a)

# using heappop() to pop smallest element
print ("The smallest element is:", heapq.heappop(a))

Output
The created heap is: [1, 3, 9, 7, 5]
The modified heap after push is: [1, 3, 4, 7, 5, 9]
The smallest element is: 1

Related Posts:

Recommended DSA Problems:

13. Graphs

Graph is a non-linear data structure consisting of a collection of nodes (or vertices) and edges (or connection between the nodes). More formally a Graph can be defined as a Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes.

Graphs

Related Posts:

Recommended DSA Problems:

14. Dynamic Programming

Dynamic Programming (DP) is a technique for solving problems by breaking them into smaller subproblems and storing their solutions to avoid redundant computations. It is used when a problem has overlapping subproblems and optimal substructure.


Related Posts:

Recommended DSA Problems:



Next Article
Article Tags :
Practice Tags :

Similar Reads