Cheatsheet
EverythingPython You Need to Know About PythonCheatsheet
# primitives
x = 1 # integer
x = 1.2 # float
x = True # bool
x = None # null
x = float('inf') # infinity (float)
# objects
x = [1, 2, 3] # list (Array)
x = (1, 2, 3) # tuple (Immutable Array)
x = {1: "a"} # dict (HashMap)
x = {1, 2, 3} # set
x = "abc123" # str (Immutable String)
n = 7
str(n) # '7'
int('7') # 7
x = [1,2,3]
set(x) # {1,2,3}
tuple(x) # (1,2,3)
s = {1,2,3}
list(s) # [3,1,2] (sets don't store order)
Basic Operations
a = [1] # array with the number 1 in it
b = [1]
a == b # True, compares value
a is b # False, compares memory location (exact comparison)
1 / 2 # .5 (division)
1 % 2 # 1 (remainder)
1 // 2 # 0 (division, rounding down)
2 ** 5 # 32 (power, 2^5)
Falsy Values
In Python, you can use anything as a boolean. Things that "feel false" like None, 0, and empty data structures evaluate to False.
a = None
b = []
c = [15]
if a:
print('This does not print')
if b:
print('This does not print')
if c:
print('This prints')
Loops with range
for i in range(4):
# 0 1 2 3
for i in range(1, 4):
# 1 2 3
for i in range(1, 6, 2): # loop in steps of 2
# 1 3 5
for i in range(3, -1, -1): # loop backwards
# 3 2 1 0
Loops over Data Structures
arr = ["a", "b"]
for x in arr:
# "a" "b"
hmap = {"a": 4, "b": 5}
for x in hmap:
# "a" "b"
List Features
x = [1,2] + [3,4] # [1,2,3,4]
x = [0, 7]*2 # [0,7,0,7], don't use this syntax for 2D arrays
x = [0,1,2,3]
x[2:] # [2,3]
x[:2] # [0,1]
x[1:4] # [1,2,3]
x[3::-1] # [3,2,1]
x[-1] # 3
y = reversed(x) # reversed array of x
x.reverse() # reverses x in-place using no extra memory
sorted(x) # sorted array of x
x.sort() # sorts x in-place using no extra memory
List Comprehensions
Python has nice syntax for creating Arrays. Here's an example:
x = [2*n for n in
Here's the general form of list comprehension, and what it's actually doing: