Python Cheatsheet

PEP8 = Bible

Numerical Work: Use NumPy by Default

Use NumPy for most numerical calculations, including individual numbers, arrays, and matrices. You generally won’t need math or cmath for this course.

1
import numpy as np

REPL & Package Management

Python’s standard REPL has no separate package or shell modes.

WhereCommandPurpose
TerminalpythonStart Python
Pythonhelp(np.sqrt)Documentation
Pythondir(np)List attributes and functions
Pythonexit()Exit
Terminalpython script.pyRun a file
Terminalpython -m pip install numpyInstall a package
Terminalpython -m pip listList installed packages
Terminalpython -m pip uninstall numpyRemove a package

On some systems, use python3 instead of python.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Create a project environment
python -m venv .venv

# Activate: macOS / Linux
source .venv/bin/activate

# Activate: Windows PowerShell
.venv\Scripts\Activate.ps1

# Install packages used below
python -m pip install numpy pandas matplotlib

Variables & Types

1
2
3
4
5
6
7
8
9
x = 55699             # int
x = 1 + 1j            # complex
x = 3.14              # float
x = True              # bool

type(x)               # check type

v = np.array([1, 2, 3])
v.dtype               # element type for a NumPy array

Arithmetic & Math

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import numpy as np

2.0 ** 2              # exponent (not ^)
np.sqrt(9)            # → 3.0
np.sqrt(-1 + 0j)      # complex input for complex result → 1j

8 / 5                 # division → 1.6
8 // 5                # floor division → 1
-8 // 5               # → -2; rounds down, unlike Julia's div

8 % 5                 # modulo → 3
-8 % 5                # → 2; like Julia's mod, not rem
np.mod(-8, 5)         # → 2; also works on arrays
np.fmod(-8, 5)        # → -3; like Julia's rem

abs(-3)               # absolute value
np.abs([-3, 2])       # element-wise absolute value

round(np.pi)          # → 3 (integer)
round(np.pi, 2)       # → 3.14
np.round(np.pi, 2)    # NumPy rounding; also works on arrays

np.pi
np.sin(np.pi / 2)
np.cos(0)
np.exp(1)
np.log(10)            # natural logarithm

Rounding to two decimal places does not force trailing zeros when displayed.


Strings

1
2
3
4
5
6
7
8
9
s = "hello"

f"{s} world"          # interpolation
s + "!"               # concatenation
len(s)
s.upper()
"a b c".split()       # → ["a", "b", "c"]

f"{3.1:.2f}"         # → "3.10"; display with 2 decimal places

Functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Anonymous function
double = lambda x: 2 * x

# Full form
def square(x):
    return x ** 2

# Optional positional + keyword-only arguments
def f(x, y=2, z=3, *, a=4.0, b=5.0):
    print([x, y, z, a, b])
    return x + y + z ** a + b

f(1)
f(1, 10, b=173, a=77)
f(1, 2, 4, b=173)

# Unpack a dictionary as keyword arguments
opts = {"a": 5.0, "b": 3.0}
f(1, 2, 4, **opts)

# Ordinary function call: no standard pipe operator
square(2)             # → 4

# Element-wise numerical operations
np.sin(np.arange(1, 6))
np.sin(np.arange(1, 6)) ** 2

Indentation defines blocks—normally four spaces. There is no end.


Control Flow

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
x = 3

# if / elif / else
if x > 0:
    print("positive")
elif x == 0:
    print("zero")
else:
    print("negative")

# Conditional expression
label = "pos" if x > 0 else "non-pos"

# for loop: stop value excluded
for i in range(1, 6):
    print(i)           # 1 through 5

# One-line if, inside a loop
for i in range(1, 6):
    if i > 3: break

# while loop
i = 1
while i <= 5:
    i += 1

# break / continue work as expected

Lists & Numerical Vectors

Use lists when you need to append or remove elements. Use NumPy arrays for numerical calculations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import numpy as np

# List
v = [1, 2, 3]

# Useful list operations
v.append(4)           # append one element in-place
v.pop()               # remove and return last element
v.extend([5, 6])      # append multiple elements
len(v)

sum(v)
max(v)                # largest element of a collection
min(v)
max(3, 7, 2)          # largest of individual values

# Filtering: new list
xv = list(range(1, 11))
odds = [x for x in xv if x % 2 != 0]

# Filtering in-place: replace the contents of the same list
# Equivalent purpose to Julia's filter!
xv[:] = [x for x in xv if x % 2 != 0]

NumPy vectors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
v = np.array([1, 2, 3])

# Row / column arrays
row = v[None, :]      # shape (1, 3)
col = v[:, None]      # shape (3, 1)

# Constructors
np.zeros(3)
np.ones(3)

rng = np.random.default_rng()
rng.random(5)         # uniform [0, 1)
rng.standard_normal(5)

# Ranges
range(1, 11)          # lazy integer range: 1 through 10
np.arange(1, 11)      # array: 1 through 10
np.linspace(0, 1, 50) # 50 points, endpoints included
np.arange(0, 1, 0.1)  # step 0.1; stop excluded

# Comprehensions & generators
arr = [x ** 2 for x in range(1, 11)]
gen = (x ** 2 for x in range(1, 11))  # lazy; no intermediate list
list(gen)             # materialize generator; consumes it

# Allocate and fill
x1 = np.empty(len(arr), dtype=float)
x1.fill(np.pi)

# Useful operations
v.sum()
v.prod()
v.max()
v.min()

np.argmin(v)          # index of smallest element (zero-based)
np.argmax(v)          # index of largest element (zero-based)

# Filtering: creates a new array
odds = v[v % 2 != 0]

Indexing & iteration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
v = np.array([1, 2, 3, 4, 5])

# Indexing: zero-based; slice stop excluded
v[0]                  # first element
v[-1]                 # last element
v[1:4]                # second through fourth elements
v[1:]                 # from second element onward

# NumPy slices usually share data with the original array
part = v[1:4]
part = v[1:4].copy()   # independent copy

# Iterate over values
for value in v:
    print(value)

# Iterate with both index and value
for i, value in enumerate(v):
    print(f"v[{i}] = {value}")

# Modify elements in-place
for i in range(len(v)):
    v[i] *= 2

# Iterate two arrays together
w = np.array([10, 20, 30, 40, 50])
for a, b in zip(v, w):
    print(a + b)

# Element-wise operations
v ** 2
np.sin(v) ** 4

# Concatenation
np.concatenate((v, v))

Lists behave differently from NumPy arrays:

1
2
[1, 2] * 2             # → [1, 2, 1, 2]
np.array([1, 2]) * 2   # → array([2, 4])

Matrices — NumPy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import numpy as np

# Literal syntax: nested lists
A = np.array([[1, 2, 3],
              [4, 5, 6]])       # 2×3 matrix

# Column-based construction
A = np.column_stack(([1, 4, 7],
                     [2, 5, 8],
                     [3, 6, 9]))

# Reshape: default fills rows first
A = np.arange(1, 10).reshape(3, 3)

# Column-first order, like Julia
A = np.arange(1, 10).reshape(3, 3, order="F")

# Constructors
np.zeros((3, 3))
np.ones((2, 4))
rng.random((3, 3))
rng.standard_normal((3, 3))
np.empty((3, 3), dtype=float)   # uninitialized
np.eye(3)                       # identity

# Indexing
A[0, 1]                         # first row, second column
A[:, 0]                         # entire first column
A[0, :]                         # entire first row

# Transpose
A.T                             # ordinary transpose
A.conj().T                      # conjugate transpose

# Concatenation
np.vstack((A, A))               # append rows
np.hstack((A, A))               # append columns

Linear algebra

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
A = np.array([[3.0, 1.0],
              [1.0, 2.0]])
B = np.eye(2)

A @ B                           # matrix multiplication
A * B                           # element-wise multiplication

np.linalg.inv(A)
np.trace(A)
np.diag(A)
np.linalg.det(A)
np.linalg.norm(A)

values, vectors = np.linalg.eig(A)
np.linalg.eigvals(A)
U, s, Vh = np.linalg.svd(A)

# Solve A @ x = b
b = np.array([9.0, 8.0])
x = np.linalg.solve(A, b)

Summation Patterns

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
N = 10

# Loop
result = 0.0
for i in range(1, N + 1):
    result += 1 / i ** 2

# List comprehension
result = sum([1 / i ** 2 for i in range(1, N + 1)])

# Generator: no intermediate list
result = sum(1 / i ** 2 for i in range(1, N + 1))

# NumPy
i = np.arange(1, N + 1, dtype=float)
result = np.sum(1 / i ** 2)

Recursion

1
2
3
4
5
6
def fac(n: int) -> int:
    if n < 0:
        raise ValueError("n must be non-negative")
    return 1 if n == 0 else n * fac(n - 1)

fac(5)                          # → 120

This function expects an integer. Type hints do not enforce types at runtime.


I/O

1
2
3
4
5
6
7
8
# User input
s = input()
x = float(input())
n = int(input())

# Output
print("hello")
print(f"x = {x:.2f}")

Numerical text files

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np

# Example: solver returns two real numbers per x
def solver(x):
    return np.sin(x), np.cos(x)

x_arr = np.linspace(0, 1, 10)

# Rows = samples; columns = x plus two solver outputs
data = np.zeros((len(x_arr), 3))

for i, x_now in enumerate(x_arr):
    data[i, :] = [x_now, *solver(x_now)]

# Overwrites an existing file
# Header automatically starts with "# "
np.savetxt("result.dat", data, delimiter="\t", header="x\ty\tz")

data2 = np.loadtxt("result.dat", delimiter="\t", comments="#")
xvec = data2[:, 0]
yvec = data2[:, 1]
zvec = data2[:, 2]

CSV & DataFrames

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import pandas as pd

# Named columns in an ordinary CSV
df = pd.DataFrame({"x": xvec, "y": yvec, "z": zvec})
df.to_csv("result.csv", index=False)

df2 = pd.read_csv("result.csv")

# Read the tab-delimited .dat file above
df3 = pd.read_csv(
    "result.dat",
    sep="\t",
    comment="#",
    header=None,
    names=["x", "y", "z"],
)

Load a Python file

1
2
3
# For a local file named myfile.py
import myfile
from myfile import solver

Plotting — Matplotlib

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 200)

fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label="sin(x)", linewidth=2)
ax.plot(x, np.cos(x), label="cos(x)", linestyle="--")

ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Trig functions")
ax.legend()

fig.tight_layout()
fig.savefig("fig.png", dpi=300)  # or .pdf, .svg
plt.show()

Introspection & Performance

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import inspect
import timeit
import dis

help(square)
inspect.signature(square)
inspect.getsource(square)      # requires available source
dis.dis(square)                # Python bytecode

# Average time per call across 10,000 calls
elapsed = timeit.timeit(lambda: square(10), number=10_000)
print(elapsed / 10_000)

In IPython / Jupyter only:

1
2
3
4
5
square?                       # help
square??                      # source, when available
%timeit square(10)             # repeated timing
%run script.py                # run a script
%pip install numpy            # install into current environment

Further Resources