Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Last Minute Notes (LMNs) – Data Structures with Python
Next article icon

User Defined Data Structures in Python

Last Updated : 26 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures:

  • Non-primitive data types: Python has list, set, and dictionary as its non-primitive data types which can also be considered its in-built data structures.
  • User-defined data structures: Data structures that aren’t supported by python but can be programmed to reflect the same functionality using concepts supported by python are user-defined data structures. There are many data structure that can be implemented this way:
    • Linked list
    • Stack
    • Queue
    • Tree
    • Graph
    • Hashmap

Linked list

A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:
 

Program:

Python3




llist = ['first', 'second', 'third']
print(llist)
 
print()
 
# adding elements
llist.append('fourth')
llist.append('fifth')
llist.insert(3, 'sixth')
print(llist)
print()
 
llist.remove('second')
print(llist)
print()
 
 

Output:

[‘first’, ‘second’, ‘third’]

[‘first’, ‘second’, ‘third’, ‘sixth’, ‘fourth’, ‘fifth’]

[‘first’, ‘third’, ‘sixth’, ‘fourth’, ‘fifth’]

Stack

A stack is a linear structure that allows data to be inserted and removed from the same end thus follows a last in first out(LIFO) system. Insertion and deletion is known as push() and pop() respectively.

Program:

Python3




stack = ['first', 'second', 'third']
print(stack)
 
print()
 
# pushing elements
stack.append('fourth')
stack.append('fifth')
print(stack)
print()
 
# printing top
n = len(stack)
print(stack[n-1])
print()
 
# popping element
stack.pop()
print(stack)
 
 

Output:

[‘first’, ‘second’, ‘third’]

[‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’]

fifth

[‘first’, ‘second’, ‘third’, ‘fourth’]

Queue

A queue is a linear structure that allows insertion of elements from one end and deletion from the other. Thus it follows, First In First Out(FIFO) methodology. The end which allows deletion is known as the front of the queue and the other end is known as the rear end of the queue. 

Program:

Python3




queue = ['first', 'second', 'third']
print(queue)
 
print()
 
# pushing elements
queue.append('fourth')
queue.append('fifth')
print(queue)
print()
 
# printing head
print(queue[0])
 
# printing tail
n = len(queue)
print(queue[n-1])
print()
 
# popping element
queue.remove(queue[0])
print(queue)
 
 

Output:

[‘first’, ‘second’, ‘third’]

[‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’]

first

fifth

[‘second’, ‘third’, ‘fourth’, ‘fifth’]

Tree

A tree is a non-linear but hierarchical data structure. The topmost element is known as the root of the tree since the tree is believed to start from the root. The elements at the end of the tree are known as its leaves. Trees are appropriate for storing data that aren’t linearly connected to each other but form a hierarchy. 

Program:

Python3




class node:
    def __init__(self, ele):
        self.ele = ele
        self.left = None
        self.right = None
 
 
def preorder(self):
    if self:
        print(self.ele)
        preorder(self.left)
        preorder(self.right)
 
 
n = node('first')
n.left = node('second')
n.right = node('third')
preorder(n)
 
 

Output:

first

second

third

Graph

A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.  A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.

Program:

Python3




class adjnode:
    def __init__(self, val):
        self.val = val
        self.next = None
 
 
class graph:
    def __init__(self, vertices):
        self.v = vertices
        self.ele = [None]*self.v
 
    def edge(self, src, dest):
        node = adjnode(dest)
        node.next = self.ele[src]
        self.ele[src] = node
 
        node = adjnode(src)
        node.next = self.ele[dest]
        self.ele[dest] = node
 
    def __repr__(self):
        for i in range(self.v):
            print("Adjacency list of vertex {}\n head".format(i), end="")
            temp = self.ele[i]
            while temp:
                print(" -> {}".format(temp.val), end="")
                temp = temp.next
 
 
g = graph(4)
g.edge(0, 2)
g.edge(1, 3)
g.edge(3, 2)
g.edge(0, 3)
g.__repr__()
 
 

Output:

Adjacency list of vertex 0

head -> 3 -> 2

Adjacency list of vertex 1

head -> 3

Adjacency list of vertex 2

head -> 3 -> 0

Adjacency list of vertex 3

head -> 0 -> 2 -> 1

Hashmap

Hash maps are indexed data structures. A hash map makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index. The key is unique and immutable. In Python, dictionaries are examples of hash maps.

Program:

Python3




def printdict(d):
    for key in d:
        print(key, "->", d[key])
 
 
hm = {0: 'first', 1: 'second', 2: 'third'}
printdict(hm)
print()
 
hm[3] = 'fourth'
printdict(hm)
print()
 
hm.popitem()
printdict(hm)
 
 

Output:

0 -> first

1 -> second

2 -> third

0 -> first

1 -> second

2 -> third

3 -> fourth

0 -> first

1 -> second

2 -> third



Next Article
Last Minute Notes (LMNs) – Data Structures with Python

V

vanshikagoyal43
Improve
Article Tags :
  • Python
  • Technical Scripter
  • Python-Data Type
  • Technical Scripter 2020
Practice Tags :
  • python

Similar Reads

  • Inbuilt Data Structures in Python
    Python has four non-primitive inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures. This article will cover the above mentioned topics. Above mentioned topics are divided into four sections below. Lists: Lists in Python are one
    3 min read
  • Python Data Structures
    Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation. Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as comp
    15+ min read
  • User Defined Data Types in C++
    User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types: Table of Content ClassStruc
    4 min read
  • Data Structures in Pandas
    Pandas is an open-source library that uses for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series. It offers a tool for cleaning and processes your data. It is the most popular Python
    4 min read
  • Last Minute Notes (LMNs) – Data Structures with Python
    Data Structures and Algorithms (DSA) are fundamental for effective problem-solving and software development. Python, with its simplicity and flexibility, provides a wide range of libraries and packages that make it easier to implement various DSA concepts. This "Last Minute Notes" article offers a q
    15+ min read
  • Python Data Structures Quizzes
    This quiz is designed to test your understanding of Python's data structures, such as list, strings, tuples, sets and dictionaries. By practicing, you’ll reinforce your knowledge and gain confidence in identifying, using and these data structures of Python. Data Structures QuizPython ListStringTuple
    1 min read
  • Viewing all defined variables in Python
    In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code. Method 1: Using dir() function dir() is a built-in function to store all the variables inside a program along with the built-in variable fu
    5 min read
  • Internal implementation of Data Structures in Python
    Python provides a variety of built-in data structures, each with its own characteristics and internal implementations optimized for specific use cases. In this article we are going to discuss about the most commonly used Data structures in Python and a brief overview of their internal implementation
    3 min read
  • How To Read .Data Files In Python?
    Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
    4 min read
  • Learn DSA with Python | Python Data Structures and Algorithms
    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. ListList is
    8 min read
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
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
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.

What kind of Experience do you want to share?

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