Skip to content
Tutorials Center
My learning

Topics

Lesson 146 of 149 ยท Practice and Review

Python Cheat Sheet

A one-page Python cheat sheet with syntax, strings, lists, dicts, sets, loops, functions, classes, errors, files, f-string formats and the most-used built-ins.

This page packs the whole course into one place: the syntax, data types and tools you'll use every day, in compact examples you can scan in seconds. Use it to refresh your memory before writing code, while working on the practice exercises, or right before an interview.

Each section links to the lesson that explains the topic in depth. A few items that trip people up most often have live editors so you can see them in action. Everything here is modern Python 3; features that need a recent version say so.

Basics

Variables, comments and output

Python
name = "Ada"                 # variables need no declaration
age: int = 36                # optional type hint
x, y = 3, 4                  # multiple assignment
x, y = y, x                  # swap
total = count = 0            # same value to several names

print("Hi", name)            # Hi Ada
print("a", "b", sep="-")     # a-b
print("no newline", end="")
answer = input("Your name? ")  # always returns a str

See Variables, Syntax and Input and Output.

Core types

Type Example Mutable?
int 42, 1_000_000, 0xFF no
float 3.14, 1e-3 no
bool True, False no
str "text", 'text', """multi-line""" no
NoneType None no
list [1, 2, 3] yes
tuple (1, 2), (1,) no
dict {"a": 1} yes
set {1, 2}, set() for empty yes

Convert with int("7"), float("2.5"), str(10), list("abc"), bool(0). Check with type(x) or, better, isinstance(x, int). See Data Types and Type Conversion.

Operators

Python
7 / 2      # 3.5   true division
7 // 2     # 3     floor division
7 % 2      # 1     remainder
2 ** 10    # 1024  power
-7 // 2    # -4    floors toward negative infinity

x += 1                     # also -=, *=, /=, //=, %=, **=
0 < x < 10                 # chained comparison
a == b, a is b             # equal value vs same object
x in items, x not in items
not a, a and b, a or b     # return one of the operands
name or "guest"            # fallback for empty values
if (n := len(items)) > 3:  # walrus: assign inside an expression
    print(n)

See Arithmetic Operators, Comparison and Logical Operators and Membership and Identity.

Strings

Python
s = "Hello, World"
s[0], s[-1], s[7:12]       # 'H', 'd', 'World'
len(s)                     # 12
s.lower(), s.upper(), s.title()
s.strip(), s.lstrip("x"), s.rstrip()
s.split(", ")              # ['Hello', 'World']
"-".join(["a", "b"])       # 'a-b'
s.replace("World", "you")
s.startswith("He"), s.endswith("!")
s.find("o"), s.count("l")  # 4, 3   (find returns -1 if missing)
"42".isdigit(), "abc".isalpha()
"ab" * 3                   # 'ababab'
r"C:\new\folder"           # raw string: backslashes stay

Strings are immutable: every method returns a new string. See Strings and String Methods.

f-strings and format specs

Spec Example Result
decimals f"{3.14159:.2f}" 3.14
thousands f"{1234567:,}" 1,234,567
percent f"{0.256:.1%}" 25.6%
width, align f"[{'ab':>5}]", f"[{'ab':<5}]", f"[{'ab':^6}]" [ ab], [ab ], [ ab ]
zero pad f"{7:03}" 007
sign f"{5:+}" +5
debug f"{x=}" x=10
dates f"{d:%Y-%m-%d}" 2026-10-14
Python Format specs in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

See String Formatting.

Lists, tuples and slicing

Python
nums = [3, 1, 4]
nums.append(1)          # [3, 1, 4, 1]
nums.extend([5, 9])     # add many
nums.insert(0, 2)       # at index 0
nums.remove(1)          # first matching value
nums.pop()              # remove + return last (pop(i) for index i)
nums.index(4), nums.count(1)
nums.sort()             # in place, returns None
sorted(nums, reverse=True)       # new list
sorted(words, key=len)           # sort by a key
nums.reverse(); nums[::-1]       # in place vs reversed copy
first, *rest = nums              # unpacking with a star
point = (3, 4); x, y = point     # tuples: fixed, immutable

Slices are seq[start:stop:step]; stop is excluded and any part can be left out.

Slice Meaning
a[2:5] items 2, 3, 4
a[:3] / a[-3:] first three / last three
a[::2] every second item
a[::-1] reversed copy
a[:] shallow copy

See Lists, List Methods, Tuples, Slicing and Unpacking.

Dictionaries and sets

Python
user = {"name": "Ana", "age": 30}
user["email"] = "[email protected]"   # add / update
user.get("phone", "n/a")            # default instead of KeyError
user.setdefault("tags", []).append("admin")
user.pop("age")                     # remove + return
"name" in user                      # checks keys
for key, value in user.items(): ...
user.keys(), user.values()
merged = defaults | user            # 3.9+: right side wins
user |= {"active": True}            # update in place

a, b = {1, 2, 3}, {3, 4}
a | b, a & b, a - b, a ^ b          # union, intersection, difference, symmetric
a.add(9); a.discard(7)              # discard never raises

See Dictionaries, Dictionary Methods and Sets. For counting and grouping, use Counter and defaultdict from collections.

Comprehensions

Python
squares = [n * n for n in range(10)]
evens = [n for n in nums if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
pairs = [(r, c) for r in range(3) for c in range(3)]
lengths = {word: len(word) for word in words}     # dict
initials = {name[0] for name in names}            # set
total = sum(n * n for n in nums)                  # generator, no list built

See List Comprehensions and Comprehensions.

Control flow

Python
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
else:
    grade = "C"
status = "adult" if age >= 18 else "minor"

for i, item in enumerate(items, start=1): ...
for a, b in zip(names, scores): ...
for n in range(10, 0, -2): ...     # 10 8 6 4 2
while attempts < 3: ...
break, continue                    # leave loop / skip to next round
for ... else:                      # else runs if the loop didn't break

match command.split():
    case ["go", direction]:
        move(direction)
    case ["quit" | "exit"]:
        stop()
    case _:
        print("Unknown")

See if Statements, for Loops, while Loops, break, continue and else and match.

Functions

Python
def greet(name: str, greeting: str = "Hello") -> str:
    """Return a greeting."""
    return f"{greeting}, {name}!"

greet("Ada"); greet("Ada", greeting="Hi")

def report(*args, **kwargs): ...      # extra positional / keyword args
def move(x, y, /, *, speed=1): ...    # positional-only / keyword-only
report(*values, **options)            # unpack when calling

square = lambda n: n * n
sorted(people, key=lambda p: p["age"])

Mutable default arguments are created once, when the function is defined, and shared by every call. Use None as the default and create the list inside.

Python The mutable default trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Scope follows LEGB: Local, Enclosing, Global, Built-in. Assigning to a name makes it local unless you declare global or nonlocal. See Functions, Arguments, Scope and Lambda.

Decorators, generators and iteration tools

Python
from functools import wraps, cache

def logged(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("calling", func.__name__)
        return func(*args, **kwargs)
    return wrapper

@cache                                 # memoize results
def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)

def countdown(n):
    while n > 0:
        yield n                        # pauses here, resumes on next()
        n -= 1

any(x > 3 for x in nums), all(nums), min(nums, key=abs)
map(str, nums), filter(None, values)   # lazy iterators

See Decorators, Generators, Iterators and itertools and functools.

Classes

Python
from dataclasses import dataclass

class Account:
    bank = "PyBank"                         # class attribute

    def __init__(self, owner: str, balance: float = 0) -> None:
        self.owner = owner                  # instance attributes
        self._balance = balance             # "_" = internal by convention

    def deposit(self, amount: float) -> None:
        self._balance += amount

    @property
    def balance(self) -> float:             # read like an attribute
        return self._balance

    @classmethod
    def empty(cls, owner): return cls(owner)

    @staticmethod
    def is_valid(amount): return amount > 0

    def __repr__(self) -> str:
        return f"Account({self.owner!r}, {self._balance})"

class Savings(Account):                     # inheritance
    def __init__(self, owner, balance=0, rate=0.02):
        super().__init__(owner, balance)
        self.rate = rate

@dataclass(order=True, frozen=True)         # __init__, __repr__, __eq__ for free
class Point:
    x: float
    y: float = 0.0

See Classes, Methods, Inheritance, Special Methods, Properties, Data Classes and Enums.

Errors and exceptions

Python
try:
    value = int(text)
except ValueError as error:
    print("Not a number:", error)
except (TypeError, KeyError):
    ...
else:
    print("runs only if no exception")
finally:
    print("always runs")

raise ValueError("age must be positive")
raise RuntimeError("save failed") from error   # keep the cause

class InsufficientFunds(Exception):
    pass

Common built-in exceptions: ValueError, TypeError, KeyError, IndexError, AttributeError, ZeroDivisionError, FileNotFoundError, StopIteration. See Exceptions, Raising Exceptions and Custom Exceptions.

Files and data

Python
from pathlib import Path
import csv, json

with open("notes.txt", "w", encoding="utf-8") as f:   # "w" "a" "r" "x"
    f.write("line 1\n")
with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())

path = Path("data") / "report.txt"
path.parent.mkdir(exist_ok=True)
path.write_text("hi", encoding="utf-8"); path.read_text(encoding="utf-8")
list(Path(".").glob("*.py"))

data = json.loads('{"a": 1}'); text = json.dumps(data, indent=2)
with open("rows.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"])

See Files, pathlib, CSV, JSON and Context Managers.

The most-used built-ins

Function What it does
len(x) number of items
range(start, stop, step) sequence of integers (stop excluded)
enumerate(it, start=0) (index, item) pairs
zip(a, b, strict=False) pairs items from several iterables
sorted(it, key=, reverse=) new sorted list
reversed(seq) reverse iterator
sum, min, max totals and extremes (key= works for min/max)
any, all is at least one / every item truthy?
map(f, it), filter(f, it) lazy transform / select
abs, round(x, n), divmod(a, b), pow(a, b, mod) number helpers
isinstance(obj, cls) type check that respects inheritance
getattr, setattr, hasattr dynamic attribute access
open(path, mode, encoding=) open a file
input(prompt), print(*items) console I/O
id(x), type(x), dir(x), help(x) inspection

Handy standard library modules

Module Use it for
math, random, statistics math functions, random choices, mean/median
datetime, zoneinfo dates, times, time zones
collections Counter, defaultdict, deque, namedtuple
itertools, functools chain, groupby, pairwise; cache, partial, reduce
re regular expressions
pathlib, os, shutil paths, folders, copying files
json, csv, sqlite3 data formats and a built-in database
asyncio concurrent I/O with async/await
logging, unittest, argparse logs, tests, command-line options

See Modules, Packages and pip and Virtual Environments.

Gotchas worth remembering

Two more classics: copying a list of lists, and comparing floats.

Python Shallow copies and float comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • is checks identity: use it only with None (if x is None). Compare values with ==.
  • Empty containers, 0, "" and None are falsy: if items: means "if the list isn't empty".
  • list.sort() returns None; sorted() returns a new list.
  • Changing a list while looping over it skips items. Loop over a copy or build a new list.
  • Closures in a loop see the variable's final value; bind it with a default argument (lambda i=i: i) if needed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does f"{0.075:.1%}" produce?

    The % spec multiplies by 100 and shows the given number of decimals.
  2. 2. Why should you avoid def add(item, items=[])?

    Defaults are evaluated once when the function is defined. Use None and create the list inside the function.
  3. 3. What is [1, 2, 3, 4, 5][::-2]?

    A step of -2 starts from the end and takes every second item.
  4. 4. Which line safely reads a dictionary key that might be missing?

    get() returns the default instead of raising KeyError. Indexing with [] raises before or is evaluated.

Summary

  • Keep this page open while you code: it covers syntax, core types, strings, collections, control flow, functions, classes, errors and files.
  • The trickiest items are format specs, mutable default arguments, shallow copies and float comparison; the live editors above show each one.
  • Every section links back to the full lesson when you need the details.

Next: Python Practice Exercises, where you'll put this cheat sheet to work on graded problems.