DEV Community

Cover image for Python Data Types & Data Structures
Mike Vincent
Mike Vincent

Posted on

Python Data Types & Data Structures

Review this guide on Python data types and data structures, and print the illustrations to help with your study.

You ever wonder why Python’s a go-to for so many developers? It’s not a mystery—it’s the data types and structures. Simple but powerful. You’ve got two groups: atomic types and composed types. One holds a single value, the other, a collection. This guide’s here to break it all down, clear the fog, and show you how to make these types work for you, no filler, no frills. Just the basics, straight up.

Primitive Data Types

These are the building blocks. The basics of Python. Simple values that are the backbone of any program.

Atomic Types

These types represent a single value. You’ll be using these all the time.

  • bool
  • int
  • float
  • complex
  • NoneType
  • str

Untitled diagram-2025-02-03-041850


Boolean Data Type

The boolean data type holds a value of either True or False. It’s simple but powerful.

Boolean Type Complexity

Time complexity: O(1)
Space complexity: O(1)
Enter fullscreen mode Exit fullscreen mode

Boolean Functions

bool()
any()
all()
not
and
or
Enter fullscreen mode Exit fullscreen mode

Boolean Examples

bool(1)               => True
bool(0)               => False
any([False, True])    => True
all([True, True])     => True
not False             => True
(True and False)      => False
(True or False)       => True
Enter fullscreen mode Exit fullscreen mode

Complex Data Type

Complex numbers have both a real and an imaginary part. This type lets you handle that.

Complex Type Complexity

Time complexity: O(1)
Space complexity: O(1)
Enter fullscreen mode Exit fullscreen mode

Complex Functions

complex()
Enter fullscreen mode Exit fullscreen mode

Complex Examples

complex(2, 3)         => (2+3j)
Enter fullscreen mode Exit fullscreen mode

Integer Data Type

Integers are whole numbers. No decimals, no fractions—just solid, raw numbers.

Integer Type Complexity

Time complexity: O(1)
Space complexity: O(1)
Enter fullscreen mode Exit fullscreen mode

Integer Functions

int()
abs()
pow()
divmod()
round()
bin()
hex()
oct()
Enter fullscreen mode Exit fullscreen mode

Integer Examples

int("42")             => 42
abs(-5)               => 5
pow(2, 3)             => 8
divmod(10, 3)         => (3, 1)
round(3.6)            => 4
bin(5)                => '0b101'
hex(255)              => '0xff'
oct(8)                => '0o10'
Enter fullscreen mode Exit fullscreen mode

NoneType Data

NoneType is used when you don’t have a value. It’s Python’s way of saying “nothing here.”

NoneType Complexity

Time complexity: O(1)
Space complexity: O(1)
Enter fullscreen mode Exit fullscreen mode

NoneType Functions

None
Enter fullscreen mode Exit fullscreen mode

NoneType Examples

None == None          => True
Enter fullscreen mode Exit fullscreen mode

Floating Point Data Type

Floats are numbers with decimals. Perfect for handling precision.

Float Type Complexity

Time complexity: O(1)
Space complexity: O(1)
Enter fullscreen mode Exit fullscreen mode

Float Functions

float()
round()
math.ceil()
math.floor()
math.sqrt()
math.exp()
math.log()
Enter fullscreen mode Exit fullscreen mode

Float Examples

float("3.14")         => 3.14
round(52.345, 2)      => 52.35
math.ceil(4.2)        => 5
math.floor(4.8)       => 4
math.sqrt(16)         => 4.0
math.exp(2)           => 7.389
math.log(8, 2)        => 3.0
Enter fullscreen mode Exit fullscreen mode

String Data Type

Strings are sequences of characters. They’re how you handle text in Python.

String Type Complexity

Time complexity: O(1) for index access
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

String Functions

ord()
chr()
str()
len()
lower()
upper()
isdigit()
Enter fullscreen mode Exit fullscreen mode

String Examples

ord('A')              => 65
chr(65)               => 'A'
str(42)               => '42'
len("hello")          => 5
"hello".lower()       => 'hello'
"hello".upper()       => 'HELLO'
"123".isdigit()       => True
Enter fullscreen mode Exit fullscreen mode

Composed Abstract Data Types

Composed data types let you work with collections of values. They make Python flexible and powerful.

Untitled diagram-2025-02-03-042353

Dictionary Data Type

Dictionaries store key-value pairs. Think of it like a phone book: a name and its number.

Dictionary Type Complexity

Time complexity: O(1) for access
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Dictionary Functions

dict()
keys()
values()
items()
get()
pop()
update()
Enter fullscreen mode Exit fullscreen mode

Dictionary Examples

dict(a=1, b=2).keys()       => ['a', 'b']
dict(a=1, b=2).values()     => [1, 2]
dict(a=1, b=2).items()      => [('a', 1), ('b', 2)]
dict(a=1, b=2).pop('a')     => 1
dict(a=1, b=2).update({'c': 3}) => {'a': 1, 'b': 2, 'c': 3}
Enter fullscreen mode Exit fullscreen mode

Heap Data Type

Heaps are trees that store data with priority. Think of a heap like a min/max priority queue. The heap data type is a tree structure where the smallest or largest value is at the root.

Heap Type Complexity

Time complexity: O(log n) for insert/remove
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Heap Functions

heapq.heappush()
heapq.heappop()
heapq.heapify()
Enter fullscreen mode Exit fullscreen mode

Heap Examples

heapq.heappush([], 3)             => [3]
heapq.heappush([], 1)             => [1, 3]
heapq.heappop([1, 3])             => 1
Enter fullscreen mode Exit fullscreen mode

Priority Queue Data Type

A priority queue stores items with a given priority. Priority queues give you a way to deal with data based on importance, not order of arrival.

Priority Queue Type Complexity

Time complexity: O(log n) for insert/remove
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Priority Queue Functions

put()
get()
empty()
task_done()
join()
Enter fullscreen mode Exit fullscreen mode

Priority Queue Examples

import queue
pq = queue.PriorityQueue()
pq.put((1, "A"))          => None
pq.put((2, "B"))          => None
pq.get()                  => (1, "A")
pq.get()                  => (2, "B")
Enter fullscreen mode Exit fullscreen mode

Queue Data Type

The queue data type is a list where items are added at one end and removed from the other. A queue works on a first-in, first-out basis, like a line at a coffee shop.

Queue Type Complexity

Time complexity: O(1) for enqueue/dequeue
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Queue Functions

collections.deque()
append()
popleft()
Enter fullscreen mode Exit fullscreen mode

Queue Examples

collections.deque([1, 2, 3]).append(4) => deque([1, 2, 3, 4])
collections.deque([1, 2, 3]).popleft() => 1
Enter fullscreen mode Exit fullscreen mode

Set Data Type

Sets store unique elements and don’t care about order.

Set Type Complexity

Time complexity: O(1) for add/remove
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Set Functions

set()
add()
remove()
union()
intersection()
difference()
Enter fullscreen mode Exit fullscreen mode

Set Examples

set([1, 2, 2, 3])      => {1, 2, 3}
{1, 2, 3}.add(4)       => {1, 2, 3, 4}
{1, 2, 3}.remove(2)    => {1, 3}
{1, 2, 3}.union({4, 5}) => {1, 2, 3, 4, 5}
{1, 2, 3}.intersection({2, 3, 4}) => {2, 3}
{1, 2, 3}.difference({2, 3}) => {1}
Enter fullscreen mode Exit fullscreen mode

Stack Data Type

A stack follows the last-in, first-out (LIFO) rule. Think of it like a stack of plates at a buffet.

Stack Type Complexity

Time complexity: O(1) for push/pop
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Stack Functions

append()
pop()
collections.deque()
Enter fullscreen mode Exit fullscreen mode

Stack Examples

stack = []
stack.append(1)        => [1]
stack.append(2)        => [1, 2]
stack.pop()            => 2
Enter fullscreen mode Exit fullscreen mode

Concrete Data Structures

Concrete data structures are the nuts and bolts of Python. They're what you use when the abstract stuff just doesn't cut it. You need something to hold your data, to let you work with it, and that's where these guys come in. Let’s break them down, section by section.

Built-in Data Structures

These are the ones that come with Python, no need to install anything. They’re the bread and butter of everyday programming.

Sequential Structures

These store stuff in a simple, ordered line. You add to the end, take from the end, and you’re good to go.

Untitled diagram-2025-02-03-043034

Array Data Type (List-Based)

An array is a simple sequence of values. It's your basic go-to structure for storing ordered items.

Array Type Complexity

Time complexity: O(1) for access
Time complexity: O(n) for insert/delete
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Array Functions

list()
len()
append()
pop()
extend()
index()
Enter fullscreen mode Exit fullscreen mode

Array Examples

len(list("abc"))                      => 3
list("abc").append("d")               => ['a', 'b', 'c', 'd']
list("abc").extend(["d", "e"])        => ['a', 'b', 'c', 'd', 'e']
list("abc").pop()                     => 'c'
list("abc").index("b")                => 1
Enter fullscreen mode Exit fullscreen mode

Dynamic Array

A dynamic array is like an array, but it can grow or shrink. Perfect for when you're not sure how much space you need upfront.

Dynamic Array Type Complexity

Time complexity: O(1) for access
Time complexity: O(n) for insert/delete
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Dynamic Array Functions

append()
insert()
remove()
resize()
Enter fullscreen mode Exit fullscreen mode

List Data Type

The list is the most versatile of the bunch. It’s mutable, which means you can change it as you go.

List Type Complexity

Time complexity: O(1) for access
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

List Functions

list()
append()
insert()
remove()
pop()
extend()
Enter fullscreen mode Exit fullscreen mode

List Examples

lst = [1, 2, 3]
lst.append(4)           => [1, 2, 3, 4]
lst.insert(1, 5)        => [1, 5, 2, 3, 4]
lst.remove(3)          => [1, 5, 2, 4]
lst.pop()               => 4
Enter fullscreen mode Exit fullscreen mode

Tuple Data Type

A tuple is like a list but locked. Once it’s set, you can’t change it. It’s perfect for when you need a fixed collection of items.

Tuple Type Complexity

Time complexity: O(1) for access
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Tuple Functions

tuple()
len()
index()
count()
Enter fullscreen mode Exit fullscreen mode

Tuple Examples

tuple([1, 2, 3])      => (1, 2, 3)
len((1, 2, 3))        => 3
(1, 2, 3).index(2)    => 1
(1, 2, 3).count(2)    => 1
Enter fullscreen mode Exit fullscreen mode

Range Data Type

Ranges store a sequence of numbers. They’re used a lot for looping and iterating.

Range Type Complexity

Time complexity: O(1) for access
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Range Functions

range()
Enter fullscreen mode Exit fullscreen mode

Range Examples

range(0, 5)           => range(0, 5)
Enter fullscreen mode Exit fullscreen mode

Linked Data Structures

These structures are all about linking nodes together, each one pointing to the next. They're flexible, efficient, and perfect for dynamic data.

Untitled diagram-2025-02-03-044022

Deque Data Type

A deque, or double-ended queue, lets you add and remove items from both ends. It’s like a queue, but twice as handy.

Deque Type Complexity

Time complexity: O(1) for append/pop at ends
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Deque Functions

collections.deque()
append()
appendleft()
pop()
popleft()
Enter fullscreen mode Exit fullscreen mode

Deque Examples

collections.deque([1, 2, 3]).append(4)   => deque([1, 2, 3, 4])
collections.deque([1, 2, 3]).appendleft(0) => deque([0, 1, 2, 3])
collections.deque([1, 2, 3]).pop()       => 3
collections.deque([1, 2, 3]).popleft()   => 1
Enter fullscreen mode Exit fullscreen mode

Linked List Data Type

The linked list is a chain of elements, where each element points to the next. It’s like a list, but it’s all pointers.

Linked List Type Complexity

Time complexity: O(1) for insert at head, O(n) for search
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Linked List Functions

insert()
delete()
search()
Enter fullscreen mode Exit fullscreen mode

Indexed Data Structures

These data structures let you access elements quickly by using an index.

Untitled diagram-2025-02-03-044315

Heap Queue Data Type

A heap queue is a priority queue based on a heap. It’s useful for managing tasks or scheduling items based on priority.

Heap Queue Type Complexity

Time complexity: O(log n) for insert/remove
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Heap Queue Functions

heapq.heappush()
heapq.heappop()
heapq.heapify()
Enter fullscreen mode Exit fullscreen mode

Heap Queue Examples

heapq.heappush([], 3)             => [3]
heapq.heappush([], 1)             => [1, 3]
heapq.heappop([1, 3])             => 1
Enter fullscreen mode Exit fullscreen mode

User-Defined Data Structures

When Python’s built-in structures aren’t enough, that’s when you roll up your sleeves and create something custom. User-defined data structures are flexible, just like your code.

Hierarchical Data Structures

These are the structures that organize data in a tree. You can think of them like a family tree, with each node pointing to its children.

Untitled diagram-2025-02-03-044416

Graph Data Type

Graphs are collections of nodes connected by edges. They’re great for modeling networks, routes, and relationships.

Graph Type Complexity

Time complexity: O(1) for edge lookup
Space complexity: O(n + m), where n is the number of nodes and m is the number of edges
Enter fullscreen mode Exit fullscreen mode

Graph Functions

add_node()
add_edge()
remove_edge()
Enter fullscreen mode Exit fullscreen mode

Graph Examples

graph = {1: [2, 3], 2: [4], 3: [4], 4: []}
Enter fullscreen mode Exit fullscreen mode

Tree Data Type

A tree organizes data in a branching structure, where each node has a parent and may have children. It’s hierarchical like a graph, but simpler.

Tree Type Complexity

Time complexity: O(log n) for search
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Tree Functions

add_child()
remove_child()
Enter fullscreen mode Exit fullscreen mode

Tree Examples

tree = {'A': ['B', 'C'], 'B': ['D'], 'C': [], 'D': []}
Enter fullscreen mode Exit fullscreen mode

Trie Data Type

A trie is a tree where each node represents part of a string. A trie stores strings in a tree-like structure. It’s perfect for quick searches, especially for tasks like autocomplete.

Trie Type Complexity

Time complexity: O(m) for search, where m is the word length
Space complexity: O(n), where n is the number of words
Enter fullscreen mode Exit fullscreen mode

Trie Functions

insert()
search()
Enter fullscreen mode Exit fullscreen mode

Trie Examples

trie = {'c': {'a': {'t': {'#': True}}, 'o': {'w': {'#': True}}}}
Enter fullscreen mode Exit fullscreen mode

Binary Tree Data Type

A binary tree is a tree where each node has at most two children. It's a simpler structure than general trees, but just as useful.

Binary Tree Type Complexity

Time complexity: O(log n) for balanced search
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Binary Tree Functions

insert()
delete()
Enter fullscreen mode Exit fullscreen mode

Binary Tree Examples

binary_tree = {'A': {'left': 'B', 'right': 'C'}, 'B': {'left': 'D', 'right': 'E'}, 'C': {}}
Enter fullscreen mode Exit fullscreen mode

Binary Search Tree Data Type

A binary search tree is like a binary tree but with a twist: it keeps the elements in sorted order to allow fast lookups.

Binary Search Tree Type Complexity

Time complexity: O(log n) for search/insert
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Binary Search Tree Functions

insert()
search()
delete()
Enter fullscreen mode Exit fullscreen mode

Binary Search Tree Examples

binary_search_tree = {'root': 'M', 'left': {'root': 'G', 'left': 'E', 'right': 'I'}, 'right': {'root': 'S', 'left': 'Q', 'right': 'Z'}}
Enter fullscreen mode Exit fullscreen mode

Hashed Data Structures

Hashed data structures use a hash function to manage data. They’re like a fast lane for data access.

Untitled diagram-2025-02-03-044541

Hash Map Data Type

A hash map stores data in key-value pairs, allowing for quick access.

Hash Map Type Complexity

Time complexity: O(1) for access
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Hash Map Functions

put()
get()
remove()
Enter fullscreen mode Exit fullscreen mode

Hash Map Examples

hash_map = {'a': 1, 'b': 2}
Enter fullscreen mode Exit fullscreen mode

Hash Set Data Type

A hash set stores unique elements using a hash function.

Hash Set Type Complexity

Time complexity: O(1) for add/remove
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

Hash Set Functions

add()
remove()
Enter fullscreen mode Exit fullscreen mode

Hash Set Examples

hash_set = {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

Third-party Data Structures

Third-party data structures are the tools you grab when the built-in stuff doesn’t fit your needs.

Untitled diagram-2025-02-03-044643

Sorted Containers Data Structures

The sortedcontainers library gives you sorted structures with fast access times.

SortedDict Data Type

A SortedDict is a dictionary that keeps its keys in sorted order.

SortedDict Type Complexity

Time complexity: O(log n) for insert/search
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

SortedDict Functions

get()
setitem()
pop()
Enter fullscreen mode Exit fullscreen mode

SortedDict Examples

from sortedcontainers import SortedDict
sorted_dict = SortedDict({2: 'b', 1: 'a'})
Enter fullscreen mode Exit fullscreen mode

SortedSet Data Type

A SortedSet is a set that keeps its elements in order.

SortedSet Type Complexity

Time complexity: O(log n) for insert/search
Space complexity: O(n)
Enter fullscreen mode Exit fullscreen mode

SortedSet Functions

add()
remove()
Enter fullscreen mode Exit fullscreen mode

SortedSet Examples

from sortedcontainers import SortedSet
sorted_set = SortedSet([3, 1, 2])
sorted_set.add(4)      => SortedSet([1, 2, 3, 4])
Enter fullscreen mode Exit fullscreen mode

Illustrations

Python Data Types & Data Structures

Python Primitive Atomic Data Types

Untitled diagram-2025-02-03-041850

Python Composed Abstract Data Types

Untitled diagram-2025-02-03-042353

Python Composed Concrete Built-In Sequential Data Structures

Untitled diagram-2025-02-03-043034

Python Composed Concrete Built-In Linked Data Structures

Untitled diagram-2025-02-03-044022

Python Composed Concrete Built-In Indexed Data Structures

Untitled diagram-2025-02-03-044315

Python Composed Concrete User-Defined Hierarchical Data Structures

Untitled diagram-2025-02-03-044416

Python Composed Concrete User-Defined Hashed Data Structures

Untitled diagram-2025-02-03-044541

Python Composed Concrete User-Defined Third-Party Sorted Containers Data Structures

Untitled diagram-2025-02-03-044643

Next Steps: Print and Review

Alright, here’s the deal: You’ve got the basics of Python data types and data structures. Now, it’s time to put it to work. Grab this guide and print it out. The illustrations? Print those too. They’re not just for decoration—they’re a map for your study.

Print, Study, and Nail It

You’re not going to remember everything in one go. That’s fine. Print this guide, toss it on your desk, keep it by your side. Use it as a reference while you dig into the code. And those illustrations? They’ll help you see the whole picture. It’s all about having the right tools when you need them.

Keep the Guide Close

This isn’t some "read once and forget" thing. Keep this guide nearby. You’ll use it over and over, especially when you're working through more complex problems or starting new projects. Think of it as your Python toolbox—keep it handy and ready to go.

And remember, when it starts to click, you’ll see how these structures fit into everything. So print it, study it, and make sure you’re ready for what comes next.


Share Your Thoughts: Python Data Types & Data Structures

Drop your thoughts in the comments. What's your favorite way to learn Python data types and data structures?


Mike Vincent is an American software engineer and writer based in Los Angeles. Mike writes about technology leadership and holds degrees in Linguistics and Industrial Automation. More about Mike Vincent

Top comments (0)