Python Cheat Sheet & Quick Reference
Python Cheat Sheet & Quick Reference
dict Mapping
bool
Set
Boolean
The Python cheat sheet is a one-page reference sheet for the Python 3 programming
language. bytes, bytearray, memoryview Binary
Slicing String
Lists
Python (python.org)
mylist = []
Learn X in Y minutes (learnxinyminutes.com)
mylist.append(1)
Regex in python (quickref.me) mylist.append(2)
for item in mylist:
print(item) # prints out 1,2
Hello World
See: Lists
>>> print("Hello, World!")
Hello, World!
If Else
File Handling
x = 1 # int
The / means quotient of x and y, and the // means floored quotient of x and y, also see
y = 2.8 # float
StackOverflow
z = 1j # complex
Plus-Equals
>>> print(type(x))
<class 'int'>
counter = 0
counter += 10 # => 10
counter = 0 Booleans
counter = counter + 10 # => 10
my_bool = True
message = "Part 1." my_bool = False
Lists x = int(1) # x will be 1
y = int(2.8) # y will be 2
list1 = ["apple", "banana", "cherry"] z = int("3") # z will be 3
list2 = [True, False, False]
list3 = [1, 5, 7, 9, 3] Floats
list4 = list((1, 5, 7, 9, 3))
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
See: Lists
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Tuple
Strings
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
Similar to List but immutable
Set
Dictionary
>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
>>> a["one"]
1
>>> a.keys()
dict_keys(['one', 'two', 'three'])
>>> a.values()
dict_values([1, 2, 3])
>>> a.update({"four": 4})
>>> a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>> a['four']
4
- Casting
Integers
Heaps
Deque is a double-ended queue with O(1) time for append/pop operations from both sides.
import heapq
myList = [9, 5, 4, 1, 3, 2]
heapq.heapify(myList) # turn myList into a Min Heap
# Python Strings
print(myList) # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # first value is always the smallest in the heap
Array-like
heapq.heappush(myList, 10) # insert 10
x = heapq.heappop(myList) # pop and return smallest item >>> hello = "Hello, World"
print(x) # => 1 >>> print(hello[1])
e
Negate all values to use Min Heap as Max Heap >>> print(hello[-1])
d
myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in myList] # multiply by -1 to negate
Get the character at position 1 or last
heapq.heapify(myList)
Looping
x = heapq.heappop(myList)
print(-x) # => 9 (making sure to multiply by -1 again)
>>> for char in "foo":
... print(char)
Heaps are binary trees for which every parent node has a value less than or equal to any of its f
children. Useful for accessing min/max value quickly. Time complexity: O(n) for heapify, O(log n) o
push and pop. See: Heapq o
Stacks and Queues Loop through the letters in the word "foo"
q = deque() # empty
┌───┬───┬───┬───┬───┬───┬───┐
q = deque([1, 2, 3]) # with values
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
q.append(4) # append to right side
0 1 2 3 4 5 6 7
q.appendleft(0) # append to left side
-7 -6 -5 -4 -3 -2 -1
print(q) # => deque([0, 1, 2, 3, 4])
Endswith
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
f-Strings Type
'{5} stars'
>>> f'{-12345:0=10}' # negative numbers
'-000012345'
>>> name = 'Eric'
>>> f'{12345:010}' # [0] shortcut (no align)
>>> age = 27
'0000012345'
>>> f"""Hello!
>>> f'{-12345:010}'
... I'm {name}.
'-000012345'
... I'm {age}."""
>>> import math # [.precision]
"Hello!\n I'm Eric.\n I'm 27."
>>> math.pi
3.141592653589793
it is available since Python 3.6, also see: Formatted string literals >>> f'{math.pi:.2f}'
'3.14'
f-Strings Fill Align >>> f'{1000000:,.2f}' # [grouping_option]
'1,000,000.00'
>>> f'{"text":10}' # [width] >>> f'{1000000:_.2f}'
'text ' '1_000_000.00'
>>> f'{"test":*>10}' # fill left >>> f'{0.25:0%}' # percentage
'******test' '25.000000%'
>>> f'{"test":*<10}' # fill right >>> f'{0.25:.0%}'
'test******' '25%'
>>> f'{"test":*^10}' # fill center
'***test***'
F-Strings Sign
>>> f'{12345:+}' # [sign] (+/-) >>> li = []
'+12345' >>> li.append(1)
>>> f'{-12345:+}' >>> li
'-12345' [1]
>>> f'{-12345:+10}' >>> li.append(2)
' -12345' >>> li
>>> f'{-12345:+010}' [1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)
>>> li1 = []
a_list[start:end]
>>> li1
a_list[start:end:step]
[]
>>> li2 = [4, 5, 6]
Slicing
>>> li2
[4, 5, 6]
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> li3 = list((1, 2, 3))
>>> a[2:5]
>>> li3 ['bacon', 'tomato', 'ham']
[1, 2, 3] >>> a[-5:-2]
>>> li4 = list(range(1, 11))
['egg', 'bacon', 'tomato']
>>> li4
>>> a[1:4]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
['egg', 'bacon', 'tomato']
Append
With a stride
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> li = [3, 1, 3, 2, 5]
>>> a[0:6:2] >>> li.sort()
['spam', 'bacon', 'ham'] >>> li
>>> a[1:6:2] [1, 2, 3, 3, 5]
['egg', 'tomato', 'lobster'] >>> li.reverse()
>>> a[6:0:-2] >>> li
['lobster', 'tomato', 'egg'] [5 3 3 2 1]
>>> a Count
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1] >>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
Remove
2
>>> li = ['bread', 'butter', 'milk']
>>> li.pop() Repeating
'milk'
>>> li >>> li = ["re"] * 3
['bread', 'butter'] >>> li
>>> del li[0] ['re', 're', 're']
>>> li
['butter']
Access
Range
primes = [2, 3, 5, 7]
for prime in primes: for i in range(4):
print(prime) print(i) # Prints: 0 1 2 3
With index
for i in range(4, 10, 2):
animals = ["dog", "cat", "mouse"] print(i) # Prints: 4 6 8
# enumerate() adds counter to an iterable
for i, value in enumerate(animals):
With zip()
print(i, value)
words = ['Mon', 'Tue', 'Wed']
Prints: 0 dog 1 cat 2 mouse nums = [1, 2, 3]
# Use zip to pack into a tuple list
for w, n in zip(words, nums):
While
print('%d:%s, ' %(n, w))
x = 0
while x < 4: Prints: 1:Mon, 2:Tue, 3:Wed,
print(x)
x += 1 # Shorthand for x = x + 1
for/else
add(5) # => 15
add(5, 20) # => 25
add(5, 6) # => 11
# Python Modules
Positional arguments Import modules
Keyword arguments
from math import ceil, floor
print(ceil(3.7)) # => 4.0
def keyword_args(**kwargs): print(floor(3.7)) # => 3.0
return kwargs
Import all
# => {"big": "foot", "loch": "ness"}
keyword_args(big="foot", loch="ness") from math import *
Default Value
import math Delete a File
import os
os.remove("myfile.txt")
Delete Folder
With line number
import os
file = open('myfile.txt', 'r') os.rmdir("myfolder")
for i, line in enumerate(file, start=1):
print("Number %s: %s" % (i, line))
- String
Write a string
Constructors
- Object
class Animal:
Write an object
def __init__(self, voice):
contents = {"aa": 12, "bb": 21} self.voice = voice
with open("myfile2.txt", "w+") as file:
file.write(json.dumps(contents)) cat = Animal('Meow')
print(cat.voice) # => Meow
Read an object
dog = Animal('Woof')
with open('myfile2.txt', "r+") as file: print(dog.voice) # => Woof
contents = json.load(file)
Method
def __repr__(self):
class Dog: return self.name
User-defined exceptions
charlie = Dog()
charlie.bark() # => "Ham-Ham" class CustomError(Exception):
pass
Class Variables
Polymorphism
class MyClass:
class_variable = "A class variable!" class ParentClass:
def print_self(self):
# => A class variable! print('A')
print(MyClass.class_variable)
class ChildClass(ParentClass):
x = MyClass() def print_self(self):
print('B')
# => A class variable!
print(x.class_variable) obj_A = ParentClass()
obj_B = ChildClass()
Super() Function
obj_A.print_self() # => A
class ParentClass: obj_B.print_self() # => B
def print_test(self):
print("Parent Method")
Overriding
Inheritance
repr() method
# Miscellaneous
Generators
def double_numbers(iterable):
for i in iterable:
yield i + i
Generator to list
Handle exceptions
try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery her
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if require
else: # Optional clause to the try/except block. Must follow al
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")
Related Cheatsheet
Recent Cheatsheet