Python cheat sheet for beginners
AdvertisementThis cheat sheet covers the Python you use every day, in the order you meet it. Every snippet was run and the output pasted from the real result (Python 3.9; everything here also works in newer versions). Keep it open next to your editor. If you want to learn the ideas behind it, the free Python video course goes through them in depth, and the Python interview questions test the same material.
Numbers
print(7/2, 7//2, 7%2, 2**10, divmod(17,5))
# 3.5 3 1 1024 (3, 2)
print(round(2.5), round(3.5), round(2.675, 2), -7//2)
# 2 4 2.67 -4
print(0.1 + 0.2, 0.1 + 0.2 == 0.3)
# 0.30000000000000004 False
/always gives a float;//floors (so-7//2is-4, not-3).round()rounds half to even (round(2.5)is 2).round(2.675, 2)is 2.67 because 2.675 cannot be stored exactly.- Compare floats with a tolerance:
abs(a - b) < 1e-9, or usemath.isclose. For money usedecimal.Decimal.
Strings
s = "Hello, World"
print(s[0], s[-1], s[7:], s[::-1])
# H d World dlroW ,olleH
print(s.lower(), s.split(", "), "-".join(["a", "b"]))
# hello, world ['Hello', 'World'] a-b
print(s.replace("l", "L", 1), s.find("World"), s.startswith("He"))
# HeLlo, World 7 True
name = "Asha"
print(f"{name!r} {3.14159:.2f} {1234567:,} {7:03d} {'x':>4}|{'x':<4}|")
# 'Asha' 3.14 1,234,567 007 x|x |
Slicing is [start:stop:step] with stop excluded; negative numbers count from the end. Strings are immutable: methods return new strings. Useful methods: strip(), upper(), title(), count(), isdigit(), format(). f-strings (f"...") support formats after a colon.
Lists
l = [3, 1, 2]
l.append(5); l.insert(0, 9); l.extend([7])
print(l) # [9, 3, 1, 2, 5, 7]
print(l.pop()) # 7 (removes and returns the last item)
l.sort()
print(l) # [1, 2, 3, 5, 9]
print(sorted(l, reverse=True), l[::2], len(l), 3 in l)
# [9, 5, 3, 2, 1] [1, 3, 9] 5 True
list.sort() sorts in place and returns None; sorted(x) returns a new list. Lists are mutable, ordered and may hold anything.
Tuples, dictionaries and sets
t = (1, 2, 3)
a, *rest = t
print(a, rest) # 1 [2, 3]
print((1,) == (1,), type((1))) # True <class 'int'> (a one-item tuple needs the comma)
d = {"a": 1, "b": 2}
d["c"] = 3
print(d.get("z"), d.get("z", 0), list(d))
# None 0 ['a', 'b', 'c']
print(list(d.items())[:2], d.pop("a"), d)
# [('a', 1), ('b', 2)] 1 {'b': 2, 'c': 3}
st = {1, 2, 3}
print(st | {3, 4}, st & {2, 3, 9}, st - {1}, st ^ {3, 4})
# {1, 2, 3, 4} {2, 3} {2, 3} {1, 2, 4}
| Type | Ordered | Mutable | Duplicates | Use |
|---|---|---|---|---|
| list | yes | yes | yes | a sequence you change |
| tuple | yes | no | yes | fixed records, keys |
| dict | yes (insertion order) | yes | unique keys | lookup by key |
| set | no | yes | no | membership, removing duplicates |
d["missing"] raises KeyError; d.get("missing") returns None.
Comprehensions and functional helpers
print([x*x for x in range(5) if x % 2 == 0]) # [0, 4, 16]
print({x: x*x for x in range(3)}) # {0: 0, 1: 1, 2: 4}
print({len(w) for w in ["aa", "bb", "c"]}) # {1, 2}
print(list(map(str.upper, ["a", "b"]))) # ['A', 'B']
print(list(filter(None, [0, 1, "", 2]))) # [1, 2]
print(list(zip([1, 2, 3], "ab")), list(enumerate("ab", 1)))
# [(1, 'a'), (2, 'b')] [(1, 'a'), (2, 'b')]
print(any([0, 1]), all([1, 0]), max([3, 9, 2]), min("bca"), sum([1, 2, 3]))
# True False 9 a 6
Functions
def f(a, b=2, *args, **kw):
return a, b, args, kw
print(f(1)) # (1, 2, (), {})
print(f(1, 3, 4, 5, x=9)) # (1, 3, (4, 5), {'x': 9})
*args collects extra positional arguments into a tuple, **kw collects keyword arguments into a dict.
The mutable default argument trap. A default value is created once, when the function is defined:
def bad(x, acc=[]):
acc.append(x)
return acc
print(bad(1)) # [1]
print(bad(2)) # [1, 2] <- the same list was reused
def good(x, acc=None):
acc = [] if acc is None else acc
acc.append(x)
return acc
print(good(1), good(2)) # [1] [2]
Scope. Use global or nonlocal to rebind an outer name:
def counter():
c = 0
def inc():
nonlocal c
c += 1
return c
return inc
i = counter()
print(i(), i()) # 1 2
Truthiness, identity and copies
print(bool([]), bool(""), bool(0), bool(None), bool("0"), bool([0]))
# False False False False True True
a = [1, 2]; b = a; c = a[:]
b.append(3)
print(a, c, a is b, a is c, a == c)
# [1, 2, 3] [1, 2] True False False
import copy
n = [[1], [2]]
sh, dp = copy.copy(n), copy.deepcopy(n)
n[0].append(9)
print(sh, dp)
# [[1, 9], [2]] [[1], [2]]
==compares values;iscompares identity (the same object). Useisonly forNone.b = adoes not copy; both names point to one list. A shallow copy shares inner lists;deepcopycopies everything.
Classes
class P:
count = 0
def __init__(self, n):
self.n = n
P.count += 1
def __repr__(self):
return f"P({self.n!r})"
@classmethod
def make(cls, n):
return cls(n)
@staticmethod
def hi():
return "hi"
@property
def up(self):
return self.n.upper()
p = P("a"); q = P.make("b")
print(p, q, P.count, P.hi(), p.up)
# P('a') P('b') 2 hi A
class C(P):
def __init__(self, n, k):
super().__init__(n)
self.k = k
def __repr__(self):
return f"C({self.n!r},{self.k})"
print(C("z", 1), isinstance(C("z", 1), P), issubclass(C, P))
# C('z',1) True True
self is the instance; @classmethod receives the class; @staticmethod receives neither; @property lets a method be read like an attribute. super() calls the parent.
Errors
try:
int("x")
except ValueError as e:
print("ValueError:", e)
else:
print("no error")
finally:
print("done")
# ValueError: invalid literal for int() with base 10: 'x'
# done
Typical messages: division by zero (ZeroDivisionError), list index out of range (IndexError), KeyError 'k'. Catch the specific exception you expect, not a bare except:.
Generators and caching
def gen(n):
for i in range(n):
yield i * i
print(list(gen(4)), sum(gen(4))) # [0, 1, 4, 9] 14
import functools
@functools.lru_cache
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
print(fib(30)) # 832040
A generator produces values one at a time and uses almost no memory. lru_cache remembers results and turns the exponential recursion into a fast one.
Files, JSON, regex and counting
with open("t.txt", "w") as fh:
fh.write("one\ntwo\n")
with open("t.txt") as fh:
print(fh.read().splitlines()) # ['one', 'two']
import json, re
print(json.dumps({"a": [1, 2], "b": None})) # {"a": [1, 2], "b": null}
print(json.loads('{"x": 1.5}')) # {'x': 1.5}
print(re.findall(r"\d+", "a1b22")) # ['1', '22']
print(re.match(r"(\w+)@(\w+)", "ada@ex").groups()) # ('ada', 'ex')
from collections import Counter, defaultdict
print(Counter("banana").most_common(2)) # [('a', 3), ('n', 2)]
dd = defaultdict(list); dd["k"].append(1)
print(dict(dd)) # {'k': [1]}
with closes the file for you, even on an error. Test patterns before you use them in code with the Regex Tester (note that Python's regex flavour differs from JavaScript in small ways), and read JSON comfortably with the JSON Formatter.
Handy built-ins and idioms
| Task | Code |
|---|---|
| Loop with index | for i, x in enumerate(items, 1): |
| Loop two lists together | for a, b in zip(xs, ys): |
| Swap | a, b = b, a |
| Chained comparison | 0 < x < 10 |
| Ternary | "yes" if ok else "no" |
| Default for None | value = x or "default" (careful: 0 and "" are falsy) |
| Unique, keep order | list(dict.fromkeys(items)) |
| Sort by key | sorted(people, key=lambda p: p["age"]) |
| Entry point | if __name__ == "__main__": |
| Read a number | int(input("n: ")) |
Reading common errors
Python's error messages name the problem and the line. Learn the usual suspects, because you will meet them every day:
| Message | Usually means |
|---|---|
SyntaxError: invalid syntax |
A missing colon, bracket or quote on or just above the reported line |
IndentationError |
Mixed tabs and spaces, or a block that is not indented |
NameError: name 'x' is not defined |
A typo, or the variable is used before it is assigned |
TypeError: can only concatenate str (not "int") to str |
Adding a string and a number; convert with str() or use an f-string |
ValueError: invalid literal for int() |
Text that is not a number was passed to int() |
IndexError: list index out of range |
The index is larger than the last position (the last index is len(l) - 1) |
KeyError: 'k' |
The dictionary has no such key; use .get() or check with in |
AttributeError: 'NoneType' object has no attribute ... |
A function returned None (often a method like sort() that works in place) |
ZeroDivisionError: division by zero |
The divisor was zero |
ModuleNotFoundError |
The package is not installed in the active environment |
Read the traceback from the bottom up: the last line is the error, and the line above it shows where it happened in your own code.
Virtual environments and packages
Keep each project's packages separate with a virtual environment:
python3 -m venv .venv # create it once per project
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requests # install a package into this environment
pip freeze > requirements.txt # record the versions
pip install -r requirements.txt # recreate the environment elsewhere
deactivate # leave the environment
Without a virtual environment, packages pile up in one global place and different projects start to conflict. Check which Python you are using with python --version and which python (or where python on Windows).
A sensible order to learn it
- Numbers, strings and
print, theninputand simple programs. if,forandwhile, plus lists and dictionaries.- Functions, then reading and writing files.
- Error handling, modules and the standard library.
- Classes and objects.
- A small project of your own, such as a quiz, a budget tracker or a file organiser.
Type everything, break it on purpose and fix it. Short daily practice beats long occasional sessions.
Style
Follow PEP 8: four-space indents, snake_case for variables and functions, PascalCase for classes, UPPER_CASE for constants. The Case Converter will convert names between styles. Prefer clear names to comments, and keep functions short.
Where to go next
Work through the Python video course (a guide to the 88 episodes is here), practise with small programs, and use the interview questions to test yourself.