Learn DSA with Python | Python Data Structures and Algorithms
Last Updated :
23 Jul, 2025
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]
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)
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:

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)
OutputInitial 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)
OutputInitial 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
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)
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))
OutputThe 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.

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:
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree 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. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem