Python Data Structures Cheat
Sheet: The Essential Guide
May 10, 2024 Cassandra Lee
Do you want to pick out elements from a list of objects but forgot how to do list
comprehension? Or maybe you have a JavaScript Object Notation (JSON) file and need to find
a suitable data structure (such as Python's dictionary data type) to process the data in it.
Browsing app development forums to find a helpful piece of Python code can be frustrating.
The good news is we’ve prepared this cheat sheet for people like you. It doubles as a
refresher on data structures and algorithms as applied to Python. Keep a copy of this Python
data structures cheat sheet on your desk to look up commands or code snippets the next
time you need to recall them.
This Python data structures cheat sheet covers the theoretical essentials. Download the PDF
version here.
Page 1 of 18
Types of Data Structures in Python
Here’s a diagram to illustrate the hierarchy of Python data structures:
Python Primitive Data Structures
These store simple data values.
DESCRIPTION EXAMPLES
Collection of characters surrounded by single or double
String 'Alice', "Bob"
quotation marks
Page 2 of 18
DESCRIPTION EXAMPLES
Boolean Logical values True, False
Integer Whole number of unlimited length 0, -273
1.618,
Float Floating-point decimal
3.1415926
Python Built-In Non-Primitive Data Structures
These data structures, which store values and collections of values, are inherent to Python.
ALLOW
DESCRIPTION ORDERED MUTABLE SYNTAX EXAMPLES
DUPLICATES
• [1, 2.3, True]
List √ √ √ [ ]
• ['John', 'Doe']
• ('age', 22)
Tuple √ √ ✕ ( )
• (7.89, False)
Set
• {6, 4.5}
0 is the same as ✕ ✕ ✕ { }
• {'nice', True}
False, as are 1 and
True.
• {"FB":
"Facebook",
Dictionary "WA":
√ > 3.7 {key: "WhatsApp",
✕ √
Map, storing key- ✕ ≤ 3.6 value} "IG":
value pairs. "Instagram"}
• {'name': 'Bob',
'id': 255}
List and Tuple Operations
Page 3 of 18
Note that Python lists and tuples are zero-indexed, meaning the first element has an index
of 0. See the command chart below for an example.
Accessing Items in Lists
The table below is based on this list:
fruit_list = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"].
COMMAND DESCRIPTION
fruit_list[0] Get the rst item on the list ("apple")
fruit_list[1] Get the second item on the list ("banana")
fruit_list[-1] Get the last item ("mango")
fruit_list[
2:5] Get the items from start to end indexes
Get the items from the beginning but exclude "kiwi" and
fruit_list[:4]
beyond
fruit_list[2:] Get the items from "cherry" to the end
Get the items from "orange" (-4) onwards but exclude "-
fruit_list[
-4:-1]
mango" (-1)
if " le" in fruit_list:
app
print(
"Yes, we have Check if "apple" is in the list
'apple'")
List (and Tuple) Methods
Commands with an asterisk (*) apply to tuples.
COMMAND DESCRIPTION USAGE
append() Add an element at the end of the list list1.a
ppend(element)
clear() Remove all the elements from the list list1.c
lear()
Page 4 of 18
COMMAND DESCRIPTION USAGE
copy() Return a copy of the list list1.c
opy()
Return the number of elements with
count() list1.c
oun
t(e
lement)
the speci ed value*
Add the elements of a list (or any
extend() list1.e end
xt (list2)
iterable), to the end of the current list
Return the index of the rst element list1.i
nde
x(e
lem
ent
[,s
-
index()
with the speci ed value* tar end]])
t[,
Add an element at the specified list1.i
nse
rt(
po
sition,
insert()
position (position is an integer) element)
Remove the element at the specified
pop() list1.p [in
op( dex])
position
Remove the rst item with the
remove() list1.r
emo
ve(
ele
ment)
speci ed value
reverse() Reverse the order of the list [Link]
verse()
sort() [Link]()
Sort the list in ascending / descending
sort(reverse = [Link](reverse =
order
True) True)
Delete from the list the item specified
del() del list1[
index]
with its index
list1 = ["x", "y"]
list2 = [8, 9]
list1 + list2 Join two lists list3 = list1 + list2
# Returns: ["x","y",8,9]
List Comprehension
List comprehension simplifies the creation of a new list based on the values of an existing
Page 5 of 18
list.
COMMAND DESCRIPTION
[n for n in range(10) if n < 5] Accept only numbers less than 5
[x for x in fruits if "
a" in x] Accept items containing "a".
[x for x in fruits if x != " le"]
app Accept all items except "app
le "
Make uppercase the values in the new
[[Link]() for x in fruits]
list
Add a question mark at the end of each
[x + '?' for x in fruits]
item
['hello' for x in fruits] Set all values in the new list to 'hello'
[x if x != " ana
ban " else "
ora
nge
" for x Replace "ban " with "ora
ana " in the
nge
in fruits] new list
Accessing Items in Tuples
Below, the tuple in question is fruits = ("apple", "banana", "cherry").
COMMAND DESCRIPTION
Check if "app
le" is present in the tuple. This command returns the
" le" in fruits
app
value True.
(x, y, z) =
fruits
# x == "apple" Assign variables to take up each item in the tuple, also known as
# y == "banana" unpacking a tuple.
# z == "cherry"
(a, *_) = fruits Either the number of variables must match the number of values in the
# a == "apple" tuple, or use an asterisk as shown to put away the unwanted values.
# _ == ["banana",
"cherry"]
Page 6 of 18
Tuple Manipulation
Adding items
You can add items to a tuple as follows:
Initial original = ("ap
ple
", "
ban
ana
", "
che
rry
")
new_item = ("or e",)
ang
Code
original += new_item
Result ("ap ", "
ple ban
ana
", "
che
rry
", "orange")
Tip: When creating a single-item tuple, remember to include a comma.
Removing items and changing values
Since tuples are immutable, you can’t remove or modify their contents directly. The key is
converting it into a list and back.
EXAMPLE ADDITION REMOVAL CHANGE
original = ("ap
- original = ("ap
- original = ("ap
-
Initial ple ban
", " ana
", "
- ple
", "
ban
ana
", "
- ple
", "
ban
ana
", "
-
che ")
rry che ")
rry che ")
rry
tempList = tempList = tempList =
→ List
list(original) list(original) list(original)
[Link] "
nd( - [Link]
ve(
"- tempList[1] = "
kiw
-
Code
ora ")
nge app
le") i"
newList = newList = newList =
→ Tuple
tuple(tempList) tuple(tempList) tuple(tempList)
Result of ("ap ", "
ple ban
ana
", ("
ban
ana
", "
che
- ("kiwi", "
ban
ana
",
newList " rry
che ", "orange") rry
") " rry
che ")
Dictionary Operations
Page 7 of 18
Adding Items
There are three methods:
EXAMPLE ADDITION #1 (DIRECT) ADDITION #2 (UPDATE()) ADDITION #3 (**)
meta = { "FB": meta = { "FB": meta = { "FB":
"Facebook", "WA": "Facebook", "WA": "Facebook", "WA":
"WhatsApp", "IG": "WhatsApp", "IG": "WhatsApp", "IG":
Initial "Instagram" } "Instagram" } "Instagram" }
new_co = { "GIF": new_co = { "GIF": new_co = { "GIF":
"Giphy" } "Giphy" } "Giphy" }
meta[
"GIF"] = meta = {**meta,
Code [Link](new_co)
"Giphy" **new_co}
{ "FB": { "FB":
{ "FB": "Facebook",
"Facebook", "WA": "Facebook", "WA":
Result of "WA": "WhatsApp", "IG":
"WhatsApp", "IG": "WhatsApp", "IG":
meta "Instagram", "GIF":
"Instagram", "Instagram",
"Giphy" }
"GIF": "Giphy" } "GIF": "Giphy" }
Warning: duplicate keys will cause the latest values to overwrite earlier values.
General Operations
COMMAND DESCRIPTION EXAMPLE
del del meta[
"WA"]
Remove the item with the speci ed key name
dict1[
"key1"] # "WhatsApp"
del di
ct1 Delete the dictionary del meta
Access the value of a dictionary dict1 meta["FB"]#
dict1[key1]
element using its key key1 "Facebook"
Dictionary method Description Usage
clear() Remove all the elements from the dictionary dict1.c
lear()
Page 8 of 18
COMMAND DESCRIPTION EXAMPLE
copy() Return a copy of the dictionary dict1.c
opy()
Return a dictionary with the specified keys dict1.f
rom
key
s(keys,
fromkeys()
and value value)
dictio
nar
y.g
et(
key
-
get() Return the value of the specified key
_name, value)
Return a list containing a tuple for each key-
items() dict1.i
tems()
value pair
keys() Return a list containing the dictionary’s keys dict1.k
eys()
pop() Remove the element with the speci ed key dict1.p
op(ke
y_name)
popitem() Remove the last inserted key-value pair dict1.p tem()
opi
Return the value of the specified key. If the dict1.s
etd
efa
ult
(ke
-
setdef
ault()
key does not exist, add as new key-value pair y_name, value)
Update the dictionary with the speci ed key- dict1.u
pda
te(
ite
-
update()
value pairs rable)
values() Return a list of all the values in the dictionary dict1.v
alues()
Set Operations
Accessing
Although you can’t directly access items in a set, you can loop through the items:
EXAMPLE ACCESSING ITEMS IN A SET (USING LIST COMPREHENSION)
set1 = {32, 1, 2, 27, 83, 26, 59, 60}
Code
set1_odd = [i for i in set1 if i % 2 == 1]
Result set1_odd = [1, 27, 83, 59]
Page 9 of 18
Adding and Removing Items
COMMAND DESCRIPTION USAGE
add() Add a single element to the set fruits.a "
dd( ora
nge
")
fruits.a {"pi
dd( nea
ppl
e", "
-
update() Add elements from another set into this set
man
go", "durian"})
discard() fruits.d
isc
ard
("ba
nan
a")
Remove the specified element
remove() fruits.r ve(
emo "ban
ana
")
Remove the last element in the set. The
pop() bye = [Link]()
return value of bye is the removed element.
clear() Empty the set [Link]()
copy() Return a copy of the set [Link]()
del Delete the set del fruits
Mathematical Operations
COMMAND / BINARY OPERATOR(S) DESCRIPTION
differ
ence()
Get the difference of several sets
-
Remove the elements in this set that are also included in
differ e_u
enc pdate()
another, speci ed set
inters ion()
ect
Get intersection of sets
&
Remove the elements in this set that are not present in
inters ion
ect _up
date()
other, specified set(s)
isdisj
oint() Return whether two sets have an intersection
issubset()
Check if a set is a (strict <) subset
<, <=
Page 10 of 18
COMMAND / BINARY OPERATOR(S) DESCRIPTION
issupe
rset()
Check if a set is a (strict >) superset
>, >=
symmet _di
ric ffe
rence()
Get symmetric difference of two sets
^
Insert the symmetric differences from this set and
symmetric_difference_update()
another
union()
Get the union of sets
|
Algorithms and the Complexities
This section is about the complexity classes of various Python data structures.
List
Tuples have the same operations (non-mutable) and complexities.
COMMAND (L: LIST) COMPLEXITY CLASS
[Link](item) O(1)
[Link]() O(1)
item in/not in L O(N)
[Link]() O(N)
del L[i] O(N)
[Link](…) O(N)
L1==L2, L1!=L2 O(N)
L[i] O(1)
for item in L: O(N)
len(L) O(1)
Page 11 of 18
COMMAND (L: LIST) COMPLEXITY CLASS
k*L O(k*N)
min(L), max(L) O(N)
[Link](-1) O(1)
[Link](item) O(N)
[Link](…) O(N)
[Link]() O(N)
L[x:y] O(y-x)
[Link]() O(N*log(N))
L[i]=item O(1)
Dictionary
COMMAND (D: DICTIONARY) COMPLEXITY CLASS / RANGE (—)
[Link]() O(1)
dict(…) O(len(d))
del d[k] O(1) — O(N)
[Link]() O(1) — O(N)
for item in d: O(N)
len(d) O(1)
[Link](item) O(1) — O(N)
[Link]() O(1)
[Link]() O(1)
[Link]() O(1)
Page 12 of 18
[Link](seq) O(len(seq))
Set
OPERATION COMMAND (S: SET) COMPLEXITY CLASS / RANGE (—)
Add [Link](item) O(1) — O(N)
Clear [Link]() O(1)
Copy [Link]() O(N)
Containment item in/not in s O(1) — O(N)
Creation set(…) O(len(s))
Discard [Link](item) O(1) — O(N)
Difference s1-s2 O(len(s1))
Difference Update s1.difference_update(s2) O(len(s2)) — ∞
Equality s1==s2, s1!=s2 O(min(len(s1), len(s2)))
Intersection s1&s2 O(min(len(s1), len(s2)))
Iteration for item in s: O(N)
Is Subset s1<=s2 O(len(s1))
Is Superset s1>=s2 O(len(s2)) — O(len(s1))
Pop [Link]() O(1) — O(N)
Union s1|s2 O(len(s1)+len(s2)) — ∞
Symmetric O(len(s1)) —
s1^s2
Difference O(len(s1)*len(s2))
Symbol Table
Python keeps track of variables using symbol tables, which you can explore using the
following basic commands:
Page 13 of 18
COMMAND DESCRIPTION
__doc__ Program documentation as comments (#, """, ''') at the beginning of the code
__name__ How you run the Python [Link] execution: __name__ == "__main__"
dir() Effective namespace
global() Dictionary of variable names of global scope to variable values
locals() Dictionary of variable names of local scope to variable values
Return the value of the speci ed variable
eval()
Example usage:for x in dir(): print(x, eval(x))
Python Libraries
The following commands are for setting up Python programs or libraries for use inside your
program:
COMMAND DESCRIPTION
import module1 Import program / library module1 as Python module
from module1 import
Import the objects obj1, obj2 from module1
obj1, obj2
from module1 import * Import all objects in module1
Return the dictionary containing module1’s symbol table, like
module1.__dict__
dir() of the main program
Examples of Python libraries containing other non-primitive data structures:
array: Efficient arrays of numeric values
collections: Abstract data structures
dataclasses: For creating user-defined data structures
datetime: Basic date and time types
queue: Synchronized queue class
Page 14 of 18