Python Cheat Sheet
Python Cheat Sheet
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:
DESCRIPTION EXAMPLES
Page 2 of 18
DESCRIPTION EXAMPLES
1.618,
Float Floating-point decimal
3.1415926
These data structures, which store values and collections of values, are inherent to Python.
ALLOW
DESCRIPTION ORDERED MUTABLE SYNTAX EXAMPLES
DUPLICATES
• ('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}
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.
COMMAND DESCRIPTION
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
Get the items from "orange" (-4) onwards but exclude "-
fruit_list[
-4:-1]
mango" (-1)
Page 4 of 18
COMMAND DESCRIPTION USAGE
sort() list1.sort()
Sort the list in ascending / descending
sort(reverse = list2.sort(reverse =
order
True) True)
# 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
['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
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
Since tuples are immutable, you can’t remove or modify their contents directly. The key is
converting it into a list and back.
original = ("ap
- original = ("ap
- original = ("ap
-
Initial ple ban
", " ana
", "
- ple
", "
ban
ana
", "
- ple
", "
ban
ana
", "
-
che ")
rry che ")
rry che ")
rry
tempList.appe "
nd( - tempList.remo
ve(
"- tempList[1] = "
kiw
-
Code
ora ")
nge app
le") i"
Dictionary Operations
Page 7 of 18
Adding Items
meta[
"GIF"] = meta = {**meta,
Code meta.update(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
del di
ct1 Delete the dictionary del meta
Page 8 of 18
COMMAND DESCRIPTION EXAMPLE
dictio
nar
y.g
et(
key
-
get() Return the value of the specified key
_name, value)
Set Operations
Accessing
Although you can’t directly access items in a set, you can loop through the items:
Page 9 of 18
Adding and Removing Items
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
")
Mathematical Operations
differ
ence()
Get the difference of several sets
-
inters ion()
ect
Get intersection of sets
&
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
^
union()
Get the union of sets
|
List
L.append(item) O(1)
L.clear() O(1)
L.copy() O(N)
L.extend(…) O(N)
L[i] O(1)
len(L) O(1)
Page 11 of 18
COMMAND (L: LIST) COMPLEXITY CLASS
k*L O(k*N)
L.pop(-1) O(1)
L.pop(item) O(N)
L.remove(…) O(N)
L.reverse() O(N)
L[x:y] O(y-x)
L.sort() O(N*log(N))
L[i]=item O(1)
Dictionary
d.clear() O(1)
dict(…) O(len(d))
len(d) O(1)
d.popitem() O(1)
d.values() O(1)
d.keys() O(1)
Page 12 of 18
d.fromkeys(seq) O(len(seq))
Set
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 program.Direct execution: __name__ == "__main__"
Python Libraries
The following commands are for setting up Python programs or libraries for use inside your
program:
COMMAND DESCRIPTION
Page 14 of 18