Python Data Structures Cheat Sheet
Python Data Structures Cheat Sheet
Cheat Sheet
\
Python Primitive Data Structures
These store simple data values.
Description Examples
String Collection of characters surrounded by 'Alice'
single or double quotation marks "Bob"
Boolean Logical values True, False
Command Description
fruit_list[1] Get the second item on the list
fruit_list[-1] Get the last item
fruit_list[-2:5] Get the items from start to end indexes
fruit_list[:4] Get the items from the beginning but
exclude "kiwi" and beyond
fruit_list[2:] Get the items from "-che-rry-" to the end
fruit_list[--4:-1] Get the items from "-ora-nge-" (-4)
onwards but exclude "-man-go" (-1)
if "-app-le" in fruit_list: Check if "-app-le" is in the list
print(-"Yes, we have 'apple'")
List Comprehension
List compre-hension simplifies the creation of a new list based on the values of an existing
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 != Accept all items except "-app-le"
"-app-le"]
[x.upper() for x in fruits] Make uppercase the values in the new list
[x + '?' for x in fruits] Add a question mark at the end of each
item
['hello' for x in fruits] Set all values in the new list to 'hello'
[x if x != "-ban-ana-" else Replace "-ban-ana-" with "-ora-nge-"
"-ora-nge-" for x in fruits] in the new list
\ # a == "apple"
# _ == ["banana", "cherry"]
Tuple Manipulation
Adding items
You can add items to a tuple as follows:
Dictionary Operations
Adding Items
There are three methods:
Example Addition #1 (direct) Addition #2 (update()) Addition #3 (**)
Initial meta = { "FB": "Facebook", "WA": "WhatsApp", "IG":
\ "Instagram" }
new_co = { "GIF": "Giphy" }
Code meta[-"GIF"] = meta.update(new_co) meta = {**meta,
"Giphy" **new_co}
Result of { "FB": "Facebook", "WA": "WhatsApp", "IG": "Instagram",
meta "GIF": "Giphy" }
Warning: duplicate keys will cause the latest values to overwrite earlier values.
General Operations
Set Operations
Accessing
Although you can’t directly access items in a set, you can loop through the items:
Mathematical Operations
\
Algorithms and the Complexities
List
Tuples have the same operations (non-mutable) and complexities.
Command (L: list) Complexity class
L.append(item) O(1)
L.clear() O(1)
item in/not in L O(N)
L.copy() O(N)
del L[i] O(N)
L.extend(…) O(N)
L1==L2, L1!=L2 O(N)
L[i] O(1)
for item in L: O(N)
len(L) O(1)
k*L O(k*N)
min(L), max(L) O(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
Command (d: dictionary) Complexity class / range (—)
d.clear() O(1)
dict(…) O(len(d))
del d[k] O(1) — O(N)
d.get() O(1) — O(N)
for item in d: O(N)
len(d) O(1)
d.pop(item) O(1) — O(N)
d.popitem() O(1)
d.values() O(1)
d.keys() O(1)
d.fromkeys(seq) O(len(seq))
Set
Operation Command (s: set) Complexity class / range (—)
Add s.add(item) O(1) — O(N)
Clear s.clear() O(1)
Copy s.copy() O(N)
Containment item in/not in s O(1) — O(N)
Creation set(…) O(len(s))
\ Discard s.discard(item) O(1) — O(N)
Difference s1-s2 O(len(s1))
Difference s1.difference_update O(len(s2)) — ∞
Update (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 s.pop() O(1) — O(N)
Union s1|s2 O(len(s1)+len(s2)) — ∞
Symmetric s1^s2 O(len(s1)) — O(len(s1)*len(s2))
Difference
Symbol Table
Python keeps track of variables using symbol tables, which you can explore using the
following basic commands:
Command Description
__doc__ Program documentation as comments (#, """, ''') at the
beginning of the code
__name__ How you run the Python program.
Direct 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
eval() Return the value of the specified variable
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 obj1, obj2 Import the objects obj1, obj2 from
module1
from module1 import * Import all objects in module1
module1.__dict__ Return the dictionary containing module1’s
symbol table, like dir() of the main program
We hope this Python data structures cheat sheet is helpful. To download a PDF version,
click here.