Skip to content
    geeksforgeeks
    • Interview Prep
      • DSA
      • Interview Corner
      • Aptitude & Reasoning
      • Practice Coding Problems
      • All Courses
    • Tutorials
      • Python
      • Java
      • ML & Data Science
      • Programming Languages
      • Web Development
      • CS Subjects
      • DevOps
      • Software and Tools
      • School Learning
    • Tracks
      • Languages
        • Python
        • C
        • C++
        • Java
        • Advanced Java
        • SQL
        • JavaScript
        • C#
      • Interview Preparation
        • GfG 160
        • GfG 360
        • System Design
        • Core Subjects
        • Interview Questions
        • Interview Puzzles
        • Aptitude and Reasoning
        • Product Management
        • Computer Organisation and Architecture
      • Data Science
        • Python
        • Data Analytics
        • Complete Data Science
        • Gen AI
        • Agentic AI
      • Dev Skills
        • Full-Stack Web Dev
        • DevOps
        • Software Testing
        • CyberSecurity
        • NextJS
        • Git
      • Tools
        • Computer Fundamentals
        • AI Tools
        • MS Excel & Google Sheets
        • MS Word & Google Docs
      • Maths
        • Maths For Computer Science
        • Engineering Mathematics
        • School Maths
    • DSA Tutorial
    • Interview Questions
    • Quizzes
    • Must Do
    • Advanced DSA
    • System Design
    • Aptitude
    • Puzzles
    • Interview Corner
    • DSA Python
    Open In App

    DSA with Python - Data Structures and Algorithms

    Last Updated : 10 Oct, 2025
    Comments
    Improve
    Suggest changes
    187 Likes
    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
    a = [10, 20, "GfG", 40, True]
    print(a)
    

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

    Related Posts:

    • Python List Guide
    • Python List Quiz

    Recommended DSA Problems:

    • Print Alternates in List
    • Search in a List
    • Largest Element
    • Reverse List
    • Check for Sorted List

    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.

    Python
    import bisect  
    a = [2, 4, 6, 8, 10]
    
    # Linear search using 'in'
    print(6 in a)       
    
    # Linear search using 'count'
    print(a.count(7) > 0)   
    
    # Binary search using bisect
    pos = bisect.bisect_left(a, 8)
    print("Found at index:", pos)
    

    Output
    True
    False
    Found at index: 3
    

    Related Posts:

    • Searching Algorithms Guide
    • Quiz on Searching

    Recommended DSA Problems:

    • Second Largest in an Array
    • First Repeating Element
    • Count Zeros in Sorted Binary Array
    • Floor in a Sorted Array
    • Maximum in Bitonic Array

    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.

    Python
    nums = [5, 3, 8, 1]
    
    # In-place sort
    nums.sort()
    print(nums)       
    
    # New sorted list (descending)
    print(sorted(nums, reverse=True))  
    

    Output
    [1, 3, 5, 8]
    [8, 5, 3, 1]
    

    Related Posts:

    • Sorting Algorithms Guide
    • Quiz on Sorting

    Recommended DSA Problems:

    • Check for Sorted Array
    • Segregate 0s and 1s
    • Wave Array
    • Merge Two Sorted Arrays
    • Intersection of Two Sorted Arrays

    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
    s = "Hello Geeks"
    print(s)
    

    Output
    Hello Geeks
    

    Related Posts:

    • Python String Guide
    • Python String Quiz

    Recommended DSA Problems:

    • Reverse a String
    • Check for Binary
    • Camel Case Conversion
    • Check for Panagram
    • Check for Palindrome

    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
    a = {10, 20, 20, "GfG", "GfG", True, True}
    print(a)
    

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

    Related Posts:

    • Python Set Guide
    • Python Set Quiz

    Recommended DSA Problems:

    • Check for Subset
    • Check for Disjoint
    • Union of Two Arrays
    • Intersection of Two Arrays
    • Pair with Given Sum

    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
    # 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:

    • Python Dictionary Guide
    • Python Dictionary Quiz

    Recommended DSA Problems:

    • Max Distance Between Two Occurrences
    • Intersection of Two Arrays
    • 2 Sum – Count pairs with given sum
    • Count pairs with given difference
    • Minimum Removals for no common

    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.

    Python
    def fact(n):
        if n == 0:
            return 1
        return n * fact(n - 1)
    
    print(fact(5))
    

    Output
    120
    

    Related Posts:

    • Python Recursion Guide
    • Python Recursion Quiz

    Recommended DSA Problems:

    • Print N to 1 without loop
    • Print N Fibonacci Numbers
    • Factorial of a Number
    • Tower of Hanoi
    • Generate Parentheses

    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.

    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:

    • Python Stack Guide

    Recommended DSA Problems:

    • Parenthesis Checker
    • Evaluation of Postfix Expression
    • Next Greater Element
    • Buildings Facing The Sun
    • Stock Span Problem

    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.

    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:

    • Python Queue Guide

    Recommended DSA Problems:

    • Stack using Two Queues
    • Sliding Window Maximum
    • BFS of Graph
    • Maximum score from at most K jumps
    • Rotten Oranges

    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.

    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:

    • Python Linked List Guide

    Recommended DSA Problems:

    • Length of Linked List
    • Search in Linked List
    • Nth Node from End
    • Middle of Linked List
    • Reverse Linked List

    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.

    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:

    • Trees in Python

    Recommended DSA Problems:

    • Inorder Traversal
    • Preorder Traversal
    • Postorder Traversal
    • Level Order Traversal
    • Height of Binary Tree
    • Search a node in BST
    • Minimum in BST
    • Floor in BST
    • Inorder Successor in BST
    • Check for BST

    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.

    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:

    • Python Heap Guide

    Recommended DSA Problems:

    • Check if Binary Tree is Heap
    • Check if Array is Heap
    • Heap Sort
    • K Largest Elements
    • Sort Nearly Sorted Array

    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.

    Python
    # Function to add an edge between two vertices
    def addEdge(adj, u, v, w):
        adj[u].append((v, w))
        adj[v].append((u, w))
    
    def displayAdjList(adj):
        for i in range(len(adj)):
            print(f"{i}: ", end="")
            for j in adj[i]:
                print(f"{{{j[0]}, {j[1]}}} ", end="")
            print()
    
    def main():
      
        # Create a graph with 3 vertices and 3 edges
        V = 3
        adj = [[] for _ in range(V)]
    
        # Now add edges one by one
        addEdge(adj, 1, 0, 4)
        addEdge(adj, 1, 2, 3)
        addEdge(adj, 2, 0, 1)
    
        print("Adjacency List Representation:")
        displayAdjList(adj)
    
    if __name__ == "__main__":
        main()
    

    Output
    Adjacency List Representation:
    0: {1, 4} {2, 1} 
    1: {0, 4} {2, 3} 
    2: {1, 3} {0, 1} 
    

    Related Posts:

    • Graphs in Python

    Recommended DSA Problems:

    • BFS of Graph
    • DFS of Graph
    • Topological Sort
    • Number of Islands
    • Check for Bipartite

    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:

    • Dynamic Programming in Python

    Recommended DSA Problems:

    • Nth Fibonacci Number
    • Nth Tribonacci Number
    • Climbing Stairs
    • Weighted Climbing Stairs
    • Nth Catalan Number
    Create Quiz

    A

    abhishek1
    Improve

    A

    abhishek1
    Improve
    Article Tags :
    • DSA
    • Python-DSA

    Explore

      DSA Fundamentals

      Logic Building Problems

      2 min read

      Analysis of Algorithms

      1 min read

      Data Structures

      Array Data Structure

      3 min read

      String in Data Structure

      2 min read

      Hashing in Data Structure

      2 min read

      Linked List Data Structure

      3 min read

      Stack Data Structure

      2 min read

      Queue Data Structure

      2 min read

      Tree Data Structure

      2 min read

      Graph Data Structure

      3 min read

      Trie Data Structure

      15+ min read

      Algorithms

      Searching Algorithms

      2 min read

      Sorting Algorithms

      3 min read

      Introduction to Recursion

      15 min read

      Greedy Algorithms

      3 min read

      Graph Algorithms

      3 min read

      Dynamic Programming or DP

      3 min read

      Bitwise Algorithms

      4 min read

      Advanced

      Segment Tree

      2 min read

      Binary Indexed Tree or Fenwick Tree

      15 min read

      Square Root (Sqrt) Decomposition Algorithm

      15+ min read

      Binary Lifting

      15+ min read

      Geometry

      2 min read

      Interview Preparation

      Interview Corner

      3 min read

      GfG160

      3 min read

      Practice Problem

      GeeksforGeeks Practice - Leading Online Coding Platform

      1 min read

      Problem of The Day - Develop the Habit of Coding

      5 min read
    top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Campus Training Program
  • Explore
  • POTD
  • Job-A-Thon
  • Blogs
  • Nation Skill Up
  • Tutorials
  • Programming Languages
  • DSA
  • Web Technology
  • AI, ML & Data Science
  • DevOps
  • CS Core Subjects
  • Interview Preparation
  • Software and Tools
  • Courses
  • ML and Data Science
  • DSA and Placements
  • Web Development
  • Programming Languages
  • DevOps & Cloud
  • GATE
  • Trending Technologies
  • Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
  • Preparation Corner
  • Interview Corner
  • Aptitude
  • Puzzles
  • GfG 160
  • System Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.
See More

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences