Sitemap
Coder’s Handbook

Useful tips regarding programming languages and technologies

Data Structures in Python

A Practical Guide to the Most Common Structures and Their Implementations

7 min readMay 14, 2026

--

Press enter or click to view image in full size
Image generated with AI

Choosing the right data structures is usually one of the keys to a good algorithm approach.

Array-Based Sequences — Centralized Versions of Lists

In Python, we consider list, tuples, and string classes as array-based sequences. They use indexing to access an individual element of the sequence. These are the most used classes when you code in Python, but they hide subtle details.

Low-Level Arrays

The primary memory of a computer is composed of bits of information grouped into larger units called bytes (8 bits). To keep track of what information is stored in what byte, the computer uses an abstraction known as a memory address. Each byte of memory is associated with a unique number that serves as its address.

Any byte of the RAM can be efficiently accessed based on its address. And we call an ARRAY a group of variables stored one after another in a contiguous portion of the computer’s memory.

A caveat of this representation is that each cell must use the same number of bytes.

Strings are a sequence of characters. Each character is Unicode in Python, which is 2 bytes. So, 6 characters are 12 bytes of memory.

A list of strings instead is saved using an internal storage mechanism of an array of object references, which is 64 bits per address. Saving the reference instead of the string avoids memory waste for saving strings directly.

Compact Arrays in Python

Strings are an array of characters, not an array of references, which makes them a compact array.

Compact arrays have several advantages over referential structures in terms of computing performance:

  • Lower memory usage: 64 bits (8 bytes) for a reference; 2 bytes for a Unicode character.
  • High-performance computing: the primary data are stored consecutively in memory, which makes them more performant.

You can use the module array to create compact arrays, but whenever you use it, you need to define the type code:

compact_array = array('i', [1, 2, 3, 4])

In this case, the type code ‘i’ designates an array of (signed) integers, typically represented using at least 16 bits.

Dynamic Arrays and Amortization

When we create a low-level array, the computer must declare explicitly its size to properly allocate a consecutive piece of memory for its storage.

Since the system might dedicate neighboring memory locations to store other data, the capacity of an array cannot be trivially increased by expanding into subsequent cells.

This problem doesn’t affect str and tuple types because they are immutable; so, once they are created, they cannot change in size.

We say that the list represents an abstraction called a dynamic array:

  • The user creates a list of 10 elements
  • The system reserves more space, predicting that the user may append new values
  • Eventually, the extra space reserved will be exhausted
  • In the latter case, the class will request a new, larger array from the system elsewhere in the memory

Efficiency of the Python’s Sequence Types

  • Len(data): O(1)
  • data[j]: O(1)
  • data.count(value): O(n)
  • data.index(value): O(k+1)
  • data.append(value): O(1) amortized. Ω(n) when resized
  • data.pop(): O(1) amortized. Omega(n) when resized
  • data.pop(k): O(n-k) amortized because of finding the value and then shifting. Ω(n) when pop(0)
  • remove(value): Ω(n). We cannot use the index to access the memory directly, so we need to find the value first and then shift the remaining elements
  • list1.extend(list2): O(m) if list2 has m elements. Also, here the list1 may be resized.

Stacks, Queues, and Deques

Stacks

Stacks represent a collection of objects that are inserted and removed according to the last-in, first-out (LIFO) principle. You can imagine the stack of plates in a cafeteria that must be cleaned.

Stacks are the simplest of all data structures, yet they are also among the most important ones.

Abstract type:

  • s.push(e): add element on top of the stack
  • s.pop(): remove and return the top element from the stack s
  • s.top(): return a reference to the top element of stack s
  • s.is_empty(): True when s is empty
  • len(s): returns the number of elements

You can easily implement a stack in Python using the list data structure:

Implementation & Time Efficiency:

  • s.push(e): l.append(e). O(1) amortized
  • s.pop(): l.pop(). O(1) amortized
  • s.top(): l[-1]. O(1)
  • s.is_empty(): len(s) == 0. O(1)
  • len(s) = len(L). O(1)

We can avoid amortization if we define the maximum capacity of a stack.

When you should use them

  • Matching parentheses and HTML tags
  • Matching tags in a Markup Language

Queues

A queue is the closest cousin of the stack. Queues are collections of objects that are inserted according to the first-in, first-out (FIFO) principle. To understand this concept, you can imagine the line of people waiting to enter a museum.

Get Stefano Lia’s stories in your inbox

Join Medium for free to get updates from this writer.

Abstract type:

  • Q.enqueue(e)
  • Q.dequeue()
  • Q.first()
  • Q.is_empty()
  • len(Q)

Array-Based Queue Implementation:

To implement a queue efficiently using a list, we should avoid using pop(0) for the dequeue() method, since it has Ω(n) time complexity due to element shifting.

Instead, we can save in the class an index that tracks the front of the queue: when we enqueue an element, we would append it to the list as usual; when we dequeue, we would return the element at the front index, set that position to None to avoid resizing and finally increment the front index.

After a while, this approach can leave many None values at the beginning of the list, wasting space. To improve this, we can reuse those empty slots instead of always appending new elements. In this case, we would have a circular array.

Time Efficiency:

Q.enqueue(e): O(1) amortizied

Q.dequeue(): O(1) amortized

Q.first(): O(1)

Q.is_empty(): O(1)

len(Q): O(1)

Related to queues, there are several similar data structures:

  • Double-Ended Queues: They support insertion and deletion at both the front and back of the queue.
  • Priority Queues: A priority queue serves the item with the highest priority first, so arrival order does not matter. If two elements have the same priority, they are typically served in insertion order.

In Python, it’s very common to use the collections.deque package because of its efficiency. It is implemented as a double‑ended queue backed by a doubly‑linked list, which allows fast insertions and deletions from both ends.

Stack with deque package:

from collections import deque

stack = deque()
stack.append("a") # push
stack.append("b")
print(stack.pop()) # "b" (top)
print(stack.pop()) # "a"

Queue with deque package:

from collections import deque

queue = deque()
queue.append("a") # enqueue at right
queue.append("b")
print(queue.popleft()) # "a" (front)
print(queue.popleft()) # "b"

Linked Lists — Distributed Representation of Lists

The Python list class is the most common and a great choice for storage, but we saw that it has disadvantages. It uses a contiguous memory layout, which can make certain operations costly.

An array provides a centralized representation of a list; alternatively, linked lists ensure a distributed representation of the collection using lightweight objects called “nodes”. Each node maintains a reference to its element and one or more references to neighboring nodes.

Unlike arrays, linked lists do not support efficient access by index

k since elements must be reached by traversing the list. However, we don’t have the problem of increasing the space when the list reaches its limit.

To add an element, we update the next reference of the last node so that it points to the new node. So, it’s all about managing the references.

This structure is useful in real-time systems where predictable operation time is critical, and amortized costs (like occasional expensive resizes) are not acceptable.

Singly Linked Lists

A singly linked list is a collection of nodes that collectively form a linear sequence. Each node stores an element and a reference to the next node in the list.

The first and last nodes of a linked list are known as the head and tail of the list. It is possible to reach the tail by traversing the list from the head, but it’s a common optimization to store a direct reference to it.

How does performance change when we implement stacks and queues using a singly linked list?

Stack with single linked list:

  • S.push(e): O(1)
  • S.pop(): O(1)
  • S.top(): O(1)
  • len(S): O(1) if you save the size of the list in the class and you mantain it every time you add or remove an element
  • S.is_empty(): O(1)

Queue with single linked list: also here all the operations are O(1)

Generally, linked lists provide a clean and flexible way to implement stacks and queues. However, array elements are contiguous: the CPU prefetches them efficiently; linked‑list nodes are scattered, causing more cache misses.

As a result, a well-implemented stack or queue using an array is often faster in practice than one based on a linked list. It’s a typical trade-off between simplicity and performance.

Circular Linked Lists

Circularly Linked Lists are linked lists in which the tail node points back to the head, forming a loop.

Circular Linked Lists are useful when you need to implement a round-robin mechanism (e.g. allocate CPU for a set of applications). Since the last node links back to the first, you can keep moving forward without explicitly restarting from the head.

When we compare this structure to a circular array (we saw it before — where “deleted” elements are often marked as None), a circular linked list avoids wasted slots entirely. Every node represents a valid element, and we would never need to check if the element is None.

Doubly Linked Lists

In a doubly linked list, each node stores references to both the next node and the previous one.

This extra reference slightly increases memory usage, but it improves the performance of the deletion and insertion of an element.

Imagine you want to delete the tail of the list using single-linked lists (which means changing the next reference of the previous to None). In this case, we would need to traverse the whole linked list to get the correct reference. In a doubly linked list, you can directly access the previous node and update its reference, avoiding that traversal.

Link-Based vs Array-Based Sequences

Array-Based Sequences:

  • They use less memory.
  • O(1) time access to an element based on an integer index.
  • Operations with equivalent asymptotic bounds typically run a constant factor more efficiently than linked-based structures.

Link-Based Sequences:

  • Provide a clear worst-case time bounds (not amortized) for their operations.
  • Can support O(1)-time insertions and deletions at arbitrary positions.

--

--

Written by Stefano Lia

Writing about the intersection of travel, technology, and personal growth.

Published in Coder’s Handbook

Useful tips regarding programming languages and technologies