Python Data Structures Operations Cheat Sheet
(with Examples)
Below are common Python data structures and typical operations—each illustrated with code
examples. The included linked list is implemented using a custom class, as Python's standard
library does not provide a built-in linked list.
1. List
Flexible, mutable, ordered sequence.
# Creation
lst = [1, 2, 3]
# Access by index
print(lst[0]) # 1
# Slicing
print(lst[1:3]) # [2, 3]
# Append
[Link](4) # [1, 2, 3, 4]
# Insert
[Link](1, 'a') # [1, 'a', 2, 3, 4]
# Remove by value
[Link]('a') # [1, 2, 3, 4]
# Remove by index
[Link](1) # returns 2; list is now [1, 3, 4]
# Check existence
print(4 in lst) # True
# Sort
[Link]() # [1, 3, 4]
# Reverse
[Link]() # [4, 3, 1]
2. Tuple
Immutable, ordered.
# Creation
tpl = (1, 2, 3)
# Access by index
print(tpl[2]) # 3
# Slicing
print(tpl[:2]) # (1, 2)
# Count value
print([Link](1)) # 1
# Find index
print([Link](2)) # 1
# Concatenate
tpl2 = tpl + (4, 5) # (1, 2, 3, 4, 5)
# Membership test
print(2 in tpl) # True
3. Set
Unordered, mutable, unique elements.
# Creation
s = {1, 2, 3}
# Add element
[Link](4) # {1, 2, 3, 4}
# Remove element
[Link](2) # {1, 3, 4}
# Discard element (no error if not present)
[Link](2)
# Union
print([Link]({5, 6})) # {1, 3, 4, 5, 6}
# Intersection
print([Link]({3, 7})) # {3}
# Subset check
print({1, 3}.issubset(s)) # True
# Membership test
print(4 in s) # True
4. Dictionary
Key-value pairs, unordered, mutable.
# Creation
d = {'a': 1, 'b': 2}
# Access by key
print(d['a']) # 1
# Set new value
d['c'] = 3
# Remove by key
[Link]('b') # {'a': 1, 'c': 3}
# Get value with default
print([Link]('b', 'not found')) # not found
# Keys, values, items
print(list([Link]())) # ['a', 'c']
print(list([Link]())) # [1, 3]
print(list([Link]())) # [('a', 1), ('c', 3)]
# Update
[Link]({'d': 4})
5. String
Immutable, ordered Unicode characters.
# Creation
s = "hello"
# Indexing and slicing
print(s[1]) # 'e'
print(s[1:4]) # 'ell'
# Length
print(len(s)) # 5
# Concatenate, repeat
print(s + " world") # 'hello world'
print(s * 2) # 'hellohello'
# Find substring
print([Link]('ll')) # 2
# Replace substring
print([Link]('l', 'x')) # 'hexxo'
# Split and join
words = 'a,b,c'.split(',') # ['a', 'b', 'c']
print(','.join(words)) # 'a,b,c'
6. Array (array module)
Efficient array with fixed data type.
from array import array
# Creation
arr = array('i', [1, 2, 3])
# Append
[Link](4) # array('i', [1, 2, 3, 4])
# Insert
[Link](0, 9) # array('i', [9, 1, 2, 3, 4])
# Remove
[Link](2) # array('i', [9, 1, 3, 4])
# Pop
val = [Link]() # Removes 4
# Slicing
print(arr[1:3]) # array('i', [1, 3])
7. Deque (collections module)
Double-ended queue.
from collections import deque
# Creation
dq = deque([1, 2, 3])
# Append right/left
[Link](4) # deque([1, 2, 3, 4])
[Link](0) # deque([0, 1, 2, 3, 4])
# Pop right/left
[Link]() # removes 4
[Link]() # removes 0
# Extend right/left
[Link]([5, 6]) # deque([1, 2, 3, 5, 6])
[Link]([-1, -2]) # deque([-2, -1, 1, 2, 3, 5, 6])
# Rotate
[Link](2) # rotates right by 2
8. Linked List (Custom Class Example)
Python does not have a built-in linked list, but it can be implemented with classes:
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class LinkedList:
def __init__(self):
[Link] = None
def append(self, data):
new_node = Node(data)
if not [Link]:
[Link] = new_node
return
curr = [Link]
while [Link]:
curr = [Link]
[Link] = new_node
def find(self, key):
curr = [Link]
while curr:
if [Link] == key:
return True
curr = [Link]
return False
def delete(self, key):
curr = [Link]
prev = None
while curr:
if [Link] == key:
if prev:
[Link] = [Link]
else:
[Link] = [Link]
return True
prev, curr = curr, [Link]
return False
def print_list(self):
curr = [Link]
while curr:
print([Link], end=" ")
curr = [Link]
print()
# Usage
ll = LinkedList()
[Link](1)
[Link](2)
[Link](3)
ll.print_list() # 1 2 3
print([Link](2)) # True
[Link](2)
ll.print_list() # 1 3
9. Other Useful Structures
NamedTuple:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y) # 1 2
Heap (Priority Queue):
import heapq
heap = []
[Link](heap, 3)
[Link](heap, 1)
print([Link](heap)) # 1
Data Structures Summary Table
Type Mutable Ordered Key Operations Example
List Yes Yes append, pop, sort
Tuple No Yes count, index
Set Yes No add, remove, union
Dict Yes No get, pop, update
String No Yes find, split, replace
Array Yes Yes append, insert, pop
Deque Yes Yes appendleft, popleft
LinkedList Yes* Yes append, delete, traverse
*Custom implementations of linked lists are mutable.