Data Structures Using Python: Lists to Graphs

Data structures using Python are built-in and library-based containers that store, organise and retrieve data efficiently. Python provides four core built-ins: list, tuple, dict and set. The standard library adds stacks, queues, heaps and graphs. Choosing the right structure determines whether your code runs in milliseconds or minutes.

Python gives you eight built-in data structures out of the box: lists, tuples, dictionaries, sets, frozensets, strings, bytes and bytearrays. Beyond those, the standard library adds stacks, queues, heaps, linked lists and graphs through modules like collections and heapq. Mastering data structures using Python means knowing which structure fits which problem and what it costs you in time and memory.

  • Python’s four core built-ins for everyday use are list, tuple, dict and set. Each has a distinct purpose and Big-O profile.
  • Stacks and queues are not separate types in Python. You build them from a list or a collections.deque.
  • Python has no built-in linked list, but you can implement one with a class in under 20 lines.
  • Graphs are typically represented with an adjacency list (a dict of lists) or an adjacency matrix (a 2-D list).
  • Interview prep tip: FAANG and top Indian product companies (Flipkart, Zomato, CRED) ask about Big-O complexity for every data structure you mention. Know it cold.

Built-In Data Structures

Before you write a single algorithm, you need to understand what Python gives you for free. If you’re just starting out, read our guide on how to write and run a Python program first so the code examples below make sense immediately.

List

A list is an ordered, mutable sequence. You can store integers, strings, objects, even other lists inside one. Indexing is O(1). Appending to the end is amortised O(1). Inserting or deleting at an arbitrary position is O(n) because Python shifts every element after the target.

Common mistake: using list.remove(value) inside a loop over the same list. Python skips elements silently. Iterate over a copy or use a list comprehension instead.

Tuple

A tuple is an ordered, immutable sequence. Use it when the data should not change: coordinates, RGB values, database rows returned by a cursor. Because tuples are immutable, Python can store them more compactly than lists, and hashing a tuple is possible (making it usable as a dict key).

Dictionary

A dict maps unique keys to values. Since Python 3.7, insertion order is guaranteed. Lookups, insertions and deletions are all average O(1) because the underlying structure is a hash table. A student roll-number-to-name mapping is a classic dict use case in Indian university lab exercises.

Set

A set stores unique, unordered elements. Membership testing (x in my_set) is O(1), which is why sets beat lists for de-duplication and intersection problems. If you need an immutable set, use frozenset.

Structure Ordered Mutable Duplicates Lookup
List Yes Yes Yes O(n)
Tuple Yes No Yes O(n)
Dict Yes (3.7+) Yes Keys: No O(1) avg
Set No Yes No O(1) avg
Frozenset No No No O(1) avg

According to the Stack Overflow Developer Survey 2024, Python is the most-used programming language among professional developers for the third year running, with 51% of respondents using it regularly. That adoption makes Python the default language for teaching and practising data structures using Python in most Indian engineering colleges today.

Stacks and Queues

These two structures come up in almost every technical interview. Knowing how to implement them cleanly in Python, without importing a special library, signals that you understand the underlying mechanics rather than just the API.

Stack (LIFO)

A stack follows Last-In, First-Out order. The classic example is your browser’s back button: each page you visit gets pushed, and clicking back pops the most recent one. In Python, a plain list works perfectly as a stack.

  • Push: stack.append(value) — O(1)
  • Pop: stack.pop() — O(1)
  • Peek: stack[-1] — O(1)

The practical tip here: never use stack.pop(0) on a list to simulate a queue. That operation is O(n) because Python shifts every remaining element. It is a subtle performance bug that costs candidates marks in live coding rounds.

Queue (FIFO)

A queue follows First-In, First-Out order, exactly like the token system at an IRCTC counter. Use collections.deque, not a list, because deque gives you O(1) appends and pops from both ends.

  • Enqueue: q.append(value)
  • Dequeue: q.popleft()

For priority queues, Python’s heapq module implements a min-heap. heapq.heappush(heap, item) and heapq.heappop(heap) both run in O(log n). This matters in Dijkstra’s shortest-path algorithm, which you will almost certainly see in a software engineering interview.

The TIOBE Index for April 2025 ranks Python at position 1 with a 23.84% share, meaning more developers are writing Python than any other language. If you are preparing for a role at an Indian IT company or a global product firm, Python-based data structures using Python problems are the baseline expectation.

Linked Lists and Trees

These two structures do not exist as built-in Python types. You build them yourself, which is exactly why interviewers love them. Writing a linked list from scratch shows you understand pointers (or references, in Python’s case), memory allocation and recursive thinking.

Linked List

Python does not have a native linked list. You create one using a Node class with a data attribute and a next attribute pointing to the next node. A singly linked list traversal is O(n). Insertion at the head is O(1). Deletion of a specific value requires traversal, so it is O(n).

On the job, you will rarely implement a linked list from scratch in production Python code. But in interviews at companies like Infosys, TCS Digital, and Wipro NLTH, you will be asked to reverse one, detect a cycle (Floyd’s algorithm), or find the middle node. Practise these until they are automatic.

Binary Tree and Binary Search Tree

A binary tree is a hierarchical structure where each node has at most two children, called left and right. A binary search tree (BST) adds the constraint that left-child values are smaller and right-child values are larger than the parent. Searching a balanced BST is O(log n). An unbalanced one degrades to O(n).

Tree traversals come up constantly in interviews. The three you must know are:

  1. In-order (Left, Root, Right): gives sorted output for a BST.
  2. Pre-order (Root, Left, Right): useful for copying a tree.
  3. Post-order (Left, Right, Root): useful for deleting a tree.

If you are studying BSc Computer Science subjects and scope, data structures and algorithms is one of the core papers where tree problems carry the most marks in university exams and placement tests alike.

Heap

A heap is a complete binary tree stored as a list. Python’s heapq module implements a min-heap by default. To simulate a max-heap, negate your values before inserting. Heaps power priority queues, scheduling algorithms and the top-K problems that show up in data engineering and AI engineering roles.

Graphs and Complexity

A graph is a collection of vertices (nodes) connected by edges. Graphs can be directed or undirected, weighted or unweighted. Social networks, Google Maps, and recommendation engines all run on graph algorithms. This is where data structures using Python get genuinely powerful, and where your understanding of time and space complexity is tested most rigorously.

Representing Graphs in Python

There are two standard approaches:

  • Adjacency list: a dict where each key is a node and the value is a list of its neighbours. Memory-efficient for sparse graphs. This is the preferred representation in most Python interview solutions.
  • Adjacency matrix: a 2-D list where matrix[i][j] = 1 means an edge exists between node i and node j. Better for dense graphs and when you need to check edge existence in O(1).

For a graph with 5 cities (Delhi, Mumbai, Bangalore, Hyderabad, Chennai), an adjacency list looks like this: {'Delhi': ['Mumbai', 'Hyderabad'], 'Mumbai': ['Bangalore'], ...}. Adding a new city is just adding a new key. That flexibility is why adjacency lists dominate in Python code.

Graph Traversal Algorithms

BFS (Breadth-First Search) uses a queue and visits all neighbours at the current depth before going deeper. It finds the shortest path in an unweighted graph. DFS (Depth-First Search) uses a stack (or recursion) and goes as deep as possible before backtracking. DFS is used for cycle detection and topological sorting.

Big-O Complexity Reference for Data Structures Using Python

Operation List Dict / Set Linked List BST (balanced) Heap
Access by index O(1) N/A O(n) O(log n) O(1) top
Search O(n) O(1) avg O(n) O(log n) O(n)
Insert O(1) end O(1) avg O(1) head O(log n) O(log n)
Delete O(n) O(1) avg O(n) O(log n) O(log n)

According to Python’s official documentation on python.org, the collections.deque is implemented as a doubly-linked list of fixed-length blocks, giving it O(1) performance on both ends. That design detail explains exactly why you should prefer deque over a list whenever you need queue behaviour in your data structures using Python implementations.

If you are working with large datasets and need NumPy arrays or Pandas DataFrames as data containers, check out our breakdown of Pandas and NumPy explained once you are comfortable with these core structures.

Strong graph skills also feed directly into AI and machine learning pipelines. Knowledge graph construction, neural network architecture (which is a directed acyclic graph), and dependency resolution all rely on the same BFS and DFS primitives you practise here. If you are thinking about that career path, our guide on how to become an AI engineer maps out the full skill stack.

For MCA students eyeing software development roles, the jobs and salary after MCA page shows you exactly which roles require deep data structure knowledge and what the pay looks like in 2025.


Frequently Asked Questions

What data structures are in Python?

Python has four primary built-in data structures: list (ordered, mutable), tuple (ordered, immutable), dict (key-value pairs, O(1) lookup) and set (unique unordered elements, O(1) membership test). The standard library extends these with collections.deque, heapq, OrderedDict and Counter, covering most practical use cases without any third-party package.

How do I implement a stack in Python?

Use a plain Python list. Call stack.append(value) to push and stack.pop() to pop. Both operations are O(1). If you need thread-safe stack behaviour in a concurrent program, use queue.LifoQueue from the standard library instead of a bare list.

Does Python have linked lists?

Python has no built-in linked list type, but collections.deque is internally implemented as a doubly-linked list of blocks, giving O(1) insertion and deletion at both ends. For interview purposes, you are expected to implement a singly or doubly linked list manually using a Node class with data and next attributes.

How are graphs represented in Python?

The two standard representations are an adjacency list (a dict mapping each node to a list of its neighbours) and an adjacency matrix (a 2-D list where matrix[i][j] indicates an edge). Adjacency lists are preferred for sparse graphs because they use less memory. For weighted graphs, store tuples of (neighbour, weight) in the list.

What is the difference between a list and a tuple in Python?

A list is mutable, meaning you can add, remove or change elements after creation. A tuple is immutable and cannot be changed once defined. Tuples use less memory, can be used as dictionary keys, and are the right choice when your data should remain constant, such as coordinates or fixed configuration values.

Which data structures are asked in Python interviews?

Indian product companies and global tech firms consistently ask about arrays and lists, hash maps (dict), stacks, queues, linked lists, binary trees, BSTs and graphs. Hash map and two-pointer problems are the most frequent in first-round coding interviews, followed by binary tree traversals and BFS/DFS on graphs. Practising data structures using Python on LeetCode and GeeksforGeeks with a focus on Big-O explanations is the most effective preparation strategy.


Where to go from here: you now have a complete map of data structures using Python, from the simplest list to graph traversal algorithms. The next step is deliberate practice.

  1. This week: implement a stack, a queue and a singly linked list from scratch without looking at notes. Then write a BFS function for a five-node graph. Time yourself.
  2. Next week: solve 10 LeetCode problems tagged “array”, “hash table” and “binary tree” in Python. Focus on getting the Big-O right, not just passing the test cases.
  3. Then: explore the software development tools to learn first to build a proper coding environment, and check out 3.0 University online certification courses in Cybersecurity, AI, Ethical Hacking and Blockchain. Strong data structure fundamentals are the foundation for secure coding, AI development and ethical hacking. If cybersecurity is your direction, the CEH v13 AI online course is a practical next step that builds directly on the programming skills you are developing now.

Last updated: May 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles