Skip to content

Python cheat sheet

Python 3 syntax on one page. Every snippet is valid Python 3.12 and opens in the in-browser Python compiler with one click.

42 entries

Basic syntax

x = 42
name = "Ada"
pi = 3.14159
is_ok = True
nothing = None

Variables need no declaration; the type comes from the value.

print(f"{name} is {x}")

f-strings interpolate expressions inside {}.

if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")

Blocks are defined by indentation (4 spaces by convention, PEP 8).

for i in range(3):
    print(i)        # 0 1 2

range(stop), range(start, stop, step).

n = 0
while n < 3:
    n += 1

while loop; use break / continue to control it.

a, b = 1, 2
a, b = b, a

Tuple unpacking swaps values without a temp variable.

match command:
    case "start":
        run()
    case "stop" | "quit":
        stop()
    case _:
        print("unknown")

Structural pattern matching (Python 3.10+).

Strings

s = "Hello, World"
s.lower(); s.upper(); s.title()

Case conversion returns a new string (strings are immutable).

s.split(", ")      # ['Hello', 'World']
", ".join(["a", "b"])  # 'a, b'

split into a list; join a list back.

s.strip(); s.replace("World", "Py")

Trim whitespace; replace substrings.

s[0]; s[-1]; s[0:5]; s[::-1]

Index, negative index, slice, reverse.

s.startswith("He"); "lo" in s; s.find("o")

Membership and search (find returns -1 if missing).

f"{3.14159:.2f}"  # '3.14'
f"{1234567:,}"   # '1,234,567'

Format spec after the colon.

Lists & tuples

nums = [3, 1, 2]
nums.append(4); nums.insert(0, 9)

Lists are mutable, ordered sequences.

nums.pop(); nums.remove(9)

pop removes by index (default last); remove by value.

sorted(nums); nums.sort(reverse=True)

sorted() returns a new list; .sort() sorts in place.

len(nums); sum(nums); max(nums); min(nums)

Common built-ins on sequences.

for i, v in enumerate(nums):
    print(i, v)

enumerate gives index and value.

for a, b in zip([1, 2], ["x", "y"]):
    print(a, b)

zip walks several iterables in parallel.

point = (3, 4)
x, y = point

Tuples are immutable; unpack them into names.

Dicts & sets

user = {"name": "Ada", "age": 36}
user["email"] = "ada@example.com"

Dicts map keys to values and keep insertion order.

user.get("phone", "n/a")

get() avoids KeyError and supplies a default.

for key, value in user.items():
    print(key, value)

Iterate over key/value pairs.

merged = user | {"age": 37}

Merge dicts (3.9+); right side wins.

tags = {"py", "js"}
tags.add("sql")
{"a", "b"} & {"b", "c"}  # {'b'}

Sets hold unique items; & | - are intersection, union, difference.

Comprehensions

[n * n for n in range(5)]

List comprehension: [0, 1, 4, 9, 16].

[n for n in range(10) if n % 2 == 0]

Filter with a trailing if.

{w: len(w) for w in ["hi", "hello"]}

Dict comprehension.

{c.lower() for c in "Hello"}

Set comprehension.

sum(n * n for n in range(1000))

Generator expression: lazy, no list is built.

Functions

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

Default parameter values.

def total(*args, **kwargs):
    return sum(args), kwargs

*args collects positional, **kwargs keyword arguments.

square = lambda x: x * x

Anonymous one-expression function.

def area(w: float, h: float) -> float:
    return w * h

Type hints (not enforced at runtime).

def countdown(n):
    while n > 0:
        yield n
        n -= 1

Generators produce values lazily with yield.

Classes

class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} says woof"

Class with constructor and method.

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float = 0.0

dataclass generates __init__, __repr__ and __eq__.

class Puppy(Dog):
    def speak(self):
        return super().speak() + "!"

Inheritance and super().

Errors & files

try:
    value = int("abc")
except ValueError as e:
    print("bad number:", e)
else:
    print("ok")
finally:
    print("done")

try / except / else / finally.

raise ValueError("amount must be positive")

Raise an exception.

with open("notes.txt", "w") as f:
    f.write("hello\n")
with open("notes.txt") as f:
    for line in f:
        print(line.strip())

with closes the file automatically.

import json
data = json.loads('{"a": 1}')
text = json.dumps(data, indent=2)

JSON to dict and back.

Frequently asked questions

Which Python version does this cheat sheet cover?

Python 3. Everything works on 3.10 and newer; the match statement needs 3.10+, dict merging with | needs 3.9+.

Can I run these snippets without installing Python?

Yes. Press Run next to a snippet and it opens in the QuickRef.dev Python compiler, which runs real CPython in your browser through WebAssembly (Pyodide).

What is the difference between a list and a tuple?

Lists are mutable, so you can add, remove and change items. Tuples are immutable, which makes them hashable (usable as dict keys) and signals that the data should not change.

Related cheat sheets