data structures in python

Python Data Structures

June 23rd, 2026
4110
10:00 Minutes

Data structure is a basic concept in computer science. It systematically puts in order and preserves data in the computer's memory. It is like a blueprint that explains how data elements can be preserved. Data structures in Python play an important part in many computational chores and are an essential concept covered in every Python tutorial. This article will give a complete guide on Python data structures and more.

What is a Data Structure?

A data structure is a way of organizing and storing essential information so it can be used efficiently. Think of it as a system or a framework that helps handle information efficiently using core Python data types and structures. This makes it easier to access, customise, and process.

Data structures help with:

  • Efficient data access - Quickly retrieving or modifying information
  • Better organization - Keeping data structured for easier management
  • Optimized performance - Making operations like searching, sorting, and storing more efficient.

Data structures are everywhere. Let us take a look at their uses.

  • Databases - To store and retrieve information efficiently
  • Search Engines - To index and find information quickly
  • Social Media Platforms - To manage user data, connections, and recommendations

Master Python Programming with Python Training

Boost your coding skills and gain hands-on knowledge in Python.

Explore Now

Types of Data Structures (With Examples)

There are different kinds of data structures, each suited for different tasks. Many of these structures are implemented using reusable Python functions and built-in libraries. Some of the most commonly used ones include:

1. Arrays

A collection of elements stored in a fixed-size sequence. Think of it like a row of lockers, each holding a specific item.

Example-

# Using a list as an array

fruits = ["apple", "banana", "cherry"]

print(fruits[1])

# Output:
# banana
Output:
banana

2. Linked Lists

A series of connected nodes where each node points to the next. It's like a chain where you can add or remove links without disturbing the entire structure.

Example-

# Basic singly linked list

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

# Create nodes
node1 = Node("A")
node2 = Node("B")
node3 = Node("C")

# Link nodes
node1.next = node2
node2.next = node3

# Traverse list
current = node1

while current:
    print(current.data)
    current = current.next

# Output:
# A
# B
# C

Output:

A
B
C

3. Stacks

Works on a "Last In, First Out" (LIFO) principle, it is similar to a stack of plates where you can only take the top one first.

Example-

# Stack implementation using a list

stack = []

stack.append("first")
stack.append("second")
stack.append("third")

print(stack.pop())

# Output:
# third

Output:

third (LIFO)

Also Explore: Pandas Cheat Sheet

4. Queues

Works on a "First In, First Out" (FIFO) basis, like a line at a ticket counter where the first person in line gets served first.

Example-

from collections import deque

# Queue implementation using deque
queue = deque()

queue.append("first")
queue.append("second")
queue.append("third")

print(queue.popleft())

# Output:
# first

Output:

first (FIFO)

5. Trees (Binary Tree)

A hierarchical structure where data is arranged in branches, like a family tree or an organizational chart.

Example-

# Binary Tree Example

class TreeNode:
    def __init__(self, value):
        self.left = None
        self.right = None
        self.value = value

# Create tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)

# In-order traversal
def inorder(node):
    if node:
        inorder(node.left)
        print(node.value)
        inorder(node.right)

inorder(root)

# Output:
# 2
# 1
# 3

6. Graphs

A collection of nodes and edges used to represent networks, such as social media connections or road maps.

Example-

# Graph representation using an adjacency list

graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "D"],
    "D": ["B", "C"]
}

# Traverse neighbors of A
print(graph["A"])

# Output:
# ['B', 'C']

Output:

['B', 'C']

7. Hash Tables

A data structure that stores data in key-value pairs, making retrieval extremely fast, like a dictionary where words (keys) map to definitions (values).

Example-

# Dictionary in Python

phone_book = {
    "Alice": "1234",
    "Bob": "5678",
    "Charlie": "9101"
}

print(phone_book["Bob"])

# Output:
# 5678

Output:

5678

Related Article- How To Learn Python From Scratch

Master Data Science with Python with Our Training Program

Boost your coding skills and gain hands-on knowledge in Data Science with Python.

Explore Now

Built-in Data Structures in Python

Python comes with multiple built-in data structures that help store and manipulate data efficiently, which is one of the biggest Python features developers rely on. These structures are easy to use and are optimized for performance, making them essential tools for any Python programmer.

Let us take a look at the main built-in data structures in Python.

1. Lists - Ordered and Mutable

A list in Python is like a flexible container that can hold multiple items, such as numbers, words, or even other lists. You can add, remove, or modify elements easily. Lists are frequently used when performing data analysis with Python and machine learning tasks.

Key Features:

Ordered - Items stay in the order you put them.

Mutable - You can change, add, or remove elements.

Supports duplicate values.

2. Tuples - Ordered and Immutable

A tuple is like a list, but once you create it, you cannot change it. This makes tuples faster and ideal for storing data that should stay constant.

Key Features:

Ordered - The order remains fixed.

Immutable - You can't change, add, or remove elements after creation.

Supports duplicate values.

3. Sets - Unordered and Unique

A set is like a basket that only keeps unique items. If you try to add the same item twice, it simply won't store duplicates.

Key Features of Sets:

Unordered - Items don't follow a specific order.

Unique - No duplicate elements are allowed.

Fast operations - Adding, removing, and checking for membership is quick.

4. Dictionaries (Dicts) - Key-Value Pairs

A dictionary is like a real-life dictionary where words (keys) have meanings (values). Instead of using an index (like lists or tuples), you access data using keys.

Key Features:

Key-Value Pairs - Information is stored in a {key: value} format.

Mutable - You can modify values, add new keys, or remove items.

Fast lookups - Accessing data by key is very efficient.

When to Use Built-in Data Structures?

  • Use a List when you need an ordered collection that may change.
  • Use a Tuple when you need an ordered collection that should stay the same.
  • Use a Set when you need to store unique items and don't care about order.
  • Use a Dictionary when you need to quickly look up values based on unique keys.

Python's built-in data structures make work easier with different types of data efficiently. Whether it's handling a list of items, storing unique values, managing constant data, or mapping keys to values, Python gives the right tool for the job. Understanding when and how to use each one will make your code faster, cleaner, and more efficient.

Related Article- Python Developer Skills You Must Learn

User-defined Data Structures in Python?

While Python gives different built-in data structures like lists, tuples, sets, and dictionaries, sometimes these are not enough for solving complex problems. That's where user-defined data structures come in.

A user-defined data structure is one that a programmer creates from scratch using Python's classes and objects. These structures are often organized using reusable Python modules. These structures allow us to organize and manage information in a way that best suits the problem we're solving.

Let us take a look at this age of user-defined data structures.

1. Stack - Last In, First Out (LIFO)

A stack is like a bunch of plates in a cafeteria. The last plate added is the first one removed. This Last In, First Out (LIFO) behavior makes stacks useful for tasks like undo/redo operations and function call management.

Key Operations:

push(value) - Adds an item to the top of the stack

pop() - Removes and returns the top item

peek() - Checks the top item without removing it

is_empty() - Checks if the stack is empty

2. Queue - First In, First Out (FIFO)

A queue is like a line at a ticket counter. The first individual in line is the first individual to be served. This First In, First Out (FIFO) structure is useful in scheduling tasks and managing resources like printer jobs.

Key Operations:

enqueue(value) - Adds an item to the end of the queue

dequeue() - Removes and returns the front item

peek() - Checks the front item without removing it

is_empty() - Checks if the queue is empty

3. Linked List - Dynamic Data Storage

A linked list is like a chain of connected nodes. Each node holds some information and a reference to the next node. Unlike lists, linked lists don't require a fixed size and are great for memory-efficient operations.

Types of Linked Lists:

Singly Linked List - Each node points to the next node.

Doubly Linked List - Each node points to both the next and previous nodes.

Circular Linked List - The last node connects back to the first node.

4. Binary Tree - Hierarchical Data Storage

A binary tree is a structure where each node has at most two children: left and right. Trees are useful for organizing hierarchical data like file systems or database indexes.

When to Use User-Defined Data Structures?

Stacks - When you need to manage operations like undo/redo or function calls.

Queues - When handling tasks in order, like customer service requests or print jobs.

Linked Lists - When frequently inserting or deleting elements, without worrying about memory allocation.

Trees - When storing hierarchical data like organization charts, file directories, or search trees.

User-defined data structures give programmers more flexibility and control over how information is handled. By designing your own stacks, queues, linked lists, or trees, you can optimize solutions for specific problems.

Understanding these structures not only improves coding skills but also helps in solving real-world problems smoothly.

Learn AI with Python with Our Latest Training Program

Boost your coding skills and gain hands-on knowledge in AI with Python.

Explore Now

Wrapping Up

Understanding data structures in Python is important for anyone working in software development or data science. Choosing the right data structure for a task can notably enhance the efficiency of your programs. Whether in building an app, a website, or analyzing data, data structures play a fundamental role in how effectively you can work with information.

FAQs: Data Structures in Python

Q1. What is the full form of DSA?

It is short for Direct Selling Agent or Data Structures and Algorithms.

Q2. For DSA, is Python better or C++?

Python is usually easier to learn for beginners, which is why many students start with a Python cheat sheet while learning DSA concepts. C++ is known for its performance and low-level, which makes it a perfect choice for mastering DSA.

Q3. What is the float function in Python?

This function converts real numbers or integers in floating point numbers.

Q4. Can I create custom Data Structures in Python?

Yes, Python supports object-oriented programming, allowing you to create custom classes for complex data structures like linked lists or trees.

About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory

Programming Certification Courses

×

Your Shopping Cart


Your shopping cart is empty.