← Back

Home › Python Cheat Sheet

Python Cheat Sheet — syntax, methods and errors on one page

Everything here is a recall aid, not a lesson. Use it when a concept already makes sense and you have only forgotten the exact method name, the argument order, or which of two similar calls returns a value and which returns None. Each section is short enough to scan in a few seconds, and the error table at the bottom pairs every common message with the one-line fix. Anything you can run is runnable in the browser playground — no installation.

Data types and mutability

Mutability is the single most consequential fact on this page. It decides what can be a dictionary key, what can go in a set, and whether a function can silently change the object you passed in.

TypeExampleMutable?Hashable (usable as a key)?
int, float5, 3.14NoYes
str"Asha"NoYes
tuple(1, 2)NoYes, unless it contains a mutable item
list[1, 2]YesNo
dict{"a": 1}YesNo
set{1, 2}YesNo
bool, NoneTypeTrue, NoneNoYes
type(x)                     # what type is this
isinstance(x, int)          # preferred type check — respects subclasses

int("42"), float("3.5"), str(42)
int(3.9)        # 3   — truncates toward zero, it does not round
round(3.9)      # 4
round(2.5)      # 2   — banker's rounding, not "round half up"
abs(-7), divmod(7, 2)      # 7, (3, 1)

f"{name} scored {score:.1f}"    # f-strings are the standard formatting
f"{rate / 100:.1%}"             # percent with one decimal
f"{value:>10}"                  # right-aligned in a 10-char field

List methods

The trap that catches almost everyone: the mutating methods return None, not the modified list. a = a.sort() leaves a holding None.

a = [3, 1, 2]

a.append(4)          # one item at the end       -> [3, 1, 2, 4]
a.extend([5, 6])     # several items             -> [3, 1, 2, 4, 5, 6]
a.insert(0, 0)       # at a position             -> [0, 3, 1, 2, 4, 5, 6]
a.remove(3)          # first matching value      -> [0, 1, 2, 4, 5, 6]
a.pop()              # removes and RETURNS last  -> 6
a.pop(0)             # removes and returns index
a.sort()             # in place, returns None
a.reverse()          # in place, returns None
a.clear()
a.count(1), a.index(1)

sorted(b)                 # RETURNS a new list — use this one
sorted(b, reverse=True)
sorted(rows, key=lambda r: r["marks"])
len(b), max(b), min(b), sum(b), any(b), all(b)

b[0], b[-1]           # first, last
b[1:3], b[:2], b[2:]  # stop is EXCLUSIVE
b[::2], b[::-1]       # step; -1 reverses
b.copy()              # shallow copy — same as b[:]
[x * 2 for x in b if x > 1]      # comprehension

String methods

Strings are immutable, so every method below returns a new string. Nothing is modified in place, and assigning the result back is your job.

s = "  Python is Fun  "

s.strip(), s.lstrip(), s.rstrip()      # trim whitespace
s.lower(), s.upper(), s.title(), s.capitalize()
s.replace("Fun", "Easy")
s.split(), s.split(","), s.split(",", 1)
"-".join(["a", "b"])                   # 'a-b' — the right way to build strings
s.startswith("Py"), s.endswith("un")
s.find("is")        # -1 if absent
s.index("is")       # raises ValueError if absent
s.count("n"), s.isdigit(), s.isalpha(), s.isalnum()
len(s), s[0], s[-1], s[::-1]           # reverse
s == s[::-1]                           # palindrome check
"key" in s                             # substring test
str(42), repr("a"), ord("A"), chr(65)

Dictionary and set

d = {"name": "Asha", "marks": 91}

d["name"]                 # KeyError if the key is absent
d.get("age", 0)           # safe — returns the default instead
"name" in d               # membership, O(1)
d.keys(), d.values(), d.items()
d["city"] = "Delhi"       # add or overwrite
d.update({"age": 20})
d.pop("age", None)        # remove with a default, so no KeyError
d.setdefault("k", [])     # get, or create then get
for k, v in d.items(): ...
{k: v for k, v in pairs}  # dict comprehension

st = {1, 2, 3}
st.add(4)
st.discard(9)             # no error if absent — remove() raises KeyError
st | {5, 6}               # union
st & {2, 3}               # intersection
st - {2}                  # difference
st ^ {3, 9}               # symmetric difference
set([1, 1, 2])            # fastest way to drop duplicates
list(dict.fromkeys(x))    # drop duplicates but KEEP the order
frozenset([1, 2])         # immutable — can be a dict key

Loops and control flow

for i in range(5):          # 0,1,2,3,4 — stop is exclusive
for i in range(2, 8):       # 2..7
for i in range(10, 0, -2):  # 10,8,6,4,2 — negative step required
for i, x in enumerate(items):          # index and item
for i, x in enumerate(items, 1):       # count from 1
for a, b in zip(one, two):             # two iterables together
for x in reversed(items): ...

while count < 10:
    count += 1              # forgetting this is the infinite loop

break        # leaves the loop entirely
continue     # skips to the next iteration
else:        # runs only if the loop finished WITHOUT break

x == y, x != y, x > y, x >= y
a and b, a or b, not a
value in items, value not in items
result = a if condition else b          # ternary
match command:                           # 3.10+ structural matching
    case "go": ...

Falsy values, which matter in every if: 0, 0.0, "", [], {}, set(), None and False. Prefer if items: over if len(items) > 0, and if x is None over if x == None.

Functions

def area(width, height=10):
    """Area of a rectangle."""        # docstring
    return width * height            # no return -> the function gives None

area(5)                          # positional
area(width=5, height=3)          # keyword
def f(*args, **kwargs): ...      # extra positional -> tuple, keyword -> dict
def f(a, *, b): ...              # b must be passed by keyword
def f(a, /, b): ...              # a must be positional

sorted(rows, key=lambda r: r["marks"])    # lambda: one expression only

def counter():                            # closure
    total = 0
    def bump():
        nonlocal total                    # enclosing scope, not global
        total += 1
    return bump

yield value        # makes the function a generator — lazy, one item at a time

@lru_cache(maxsize=None)   # memoise a recursive function

Never use a mutable default argument. def f(x, box=[]) creates the list once, at definition time, so every call shares it. Use box=None and build it inside.

Comprehensions

[x * 2 for x in nums]                        # list
[x for x in nums if x > 0]                   # with a filter
[x if x > 0 else 0 for x in nums]            # transform every item
[(i, j) for i in range(2) for j in range(2)] # nested, reads left to right
{k: v for k, v in pairs}                     # dict
{x for x in nums}                            # set
(x * 2 for x in nums)                        # generator — lazy

# a full if/else does not fit in a comprehension — use a loop
[[0] * 3 for _ in range(3)]                  # correct way to build a grid

Use a comprehension when it reads in one pass. If you need a break, an except, or more than one if, write the loop — a comprehension that needs explaining is worse than the loop it replaced.

Errors and their one-line fix

MessageFix
SyntaxErrorThe file never ran. Check the colon, the bracket and the quotes — and look at the line above the one reported.
IndentationError / TabErrorTabs and spaces are mixed. Convert the whole file to 4 spaces per level.
NameErrorThe name exists in no scope — spelling, or defined after use. See the NameError guide.
UnboundLocalErrorAssigning anywhere in a function makes the name local for the whole function. Use global, nonlocal, or pass it in.
TypeErrorWrong type for the operation. Put print(type(x)) on the line before.
ValueErrorRight type, wrong value — int("abc"). Validate before converting.
KeyErrorThe dict has no such key. Use d.get(k, default) or test k in d first.
IndexErrorIndex out of range — the last valid index is len(x) - 1.
AttributeErrorNo such method or attribute. sort() belongs to a list, not a string.
ZeroDivisionErrorDividing by zero, usually an empty list's length. Guard with if items:.
FileNotFoundErrorRelative paths start at the working directory. Use Path(__file__).parent / name.
ModuleNotFoundErrorNot installed, misspelled, or the wrong environment is active.
try:
    value = int(raw)
except ValueError as e:
    print(f"not a number: {e}")
else:
    print("worked")        # only when no exception was raised
finally:
    cleanup()              # always — even after a return

raise ValueError("clear message")   # raise your own

Read every traceback bottom-up: the last line names the exception, the lines above show how execution got there, and the deepest frame is the useful one. The full error explainer has a dedicated page for each message above.

The four rules that prevent most beginner bugs

  1. sort(), append() and friends return None. Use sorted() when you need the value back.
  2. A slice's stop is exclusive. s[1:3] gives two items, and range(1, 10) stops at 9.
  3. input() always returns a string. Convert at the point of entry, before any arithmetic.
  4. b = a is not a copy. It is a second name for the same object; use a.copy() or copy.deepcopy(a).

Those four account for a large share of all beginner bugs. Practise them until they are automatic — the practice hub turns each one into a bug you fix rather than a rule you re-read.

Frequently asked questions

Can you learn Python from a cheat sheet?

Not from one alone. It is a recall aid that works once the concept already makes sense and you have only forgotten the exact name or syntax. Learn the topic properly first, then revise here.

What are the most commonly forgotten rules?

That sort() and append() return None; that a slice's stop is exclusive; that input() returns a string; and that range(1, 10) stops at 9. Those four remove roughly half of all beginner bugs.

Why does mutability matter?

It decides whether a value can be a dict key or set member, whether a function can change your original object, and whether b = a gives you a copy or an alias. Lists, dicts and sets are mutable; numbers, strings, tuples and None are not.

What should I revise before an interview?

Data types and mutability, the methods on list, tuple, dict and set, break and continue, function scope and default arguments, and the error messages with their fixes — then practise output prediction daily. See the interview questions page.

Is there a Hindi version?

Yes — the same reference in Hindi is at Python cheat sheet (Hindi), part of the wider Hindi hub.