Python Cheat Sheet
Basics
// Print and read input
print("Hello", name, sep=", ", end="\n")
x = int(input())
a, b = map(int, input().split())
nums = list(map(int, input().split()))
// f-strings
print(f"{name} has {score:.2f} points")
// Type conversion
int("42"); float("3.5"); str(10); list("abc")
Strings
s.upper(); s.lower(); s.strip()
s.split(","); ",".join(words)
s.replace("a", "b"); s.find("x"); s.count("a")
s[::-1]
s.startswith("ab"); s.isdigit(); s.isalpha()
Lists
a.append(x); a.extend([1, 2]); a.insert(i, x)
a.pop(); a.pop(i); a.remove(x)
a.sort(); a.sort(reverse=True); sorted(a, key=len)
a.index(x); a.count(x); a.reverse()
[x * 2 for x in a if x > 0]
a[1:4]; a[::-1]; len(a); sum(a); max(a); min(a)
Dict, set, tuple
d = {"a": 1}; d["b"] = 2; d.get("z", 0)
d.keys(); d.values(); d.items()
d.pop("a"); "a" in d
s = set(); s.add(1); s.discard(1); a | b; a & b; a - b
t = (1, 2); x, y = t
Control flow
// if / elif / else
if x > 0: print("pos")
elif x == 0: print("zero")
else: print("neg")
// loops
for i in range(n): pass
for i, v in enumerate(a): pass
for a_item, b_item in zip(a, b): pass
while x > 0: x -= 1
Functions and classes
def f(a, b=2, *args, **kwargs): return a + b
square = lambda x: x * x
class Dog:
def __init__(self, name): self.name = name
def speak(self): return f"{self.name} says woof"
Errors and files
try:
risky()
except ValueError as e:
print(e)
finally:
cleanup()
with open("file.txt") as f: text = f.read()
Useful modules
from collections import Counter, defaultdict, deque
import heapq; heapq.heappush(h, x); heapq.heappop(h)
from functools import lru_cache
import math; math.gcd(a, b); math.sqrt(x); math.inf
import bisect; bisect.bisect_left(a, x)
pip and virtual environments
// Run these in the terminal
python -m venv .venv
pip install requests
pip freeze > requirements.txt
Full Python documentation