Python Cheat Sheet
A complete quick reference guide for Python syntax, data types, control flow, functions, OOP, modules, and algorithms. Keep this handy.
Welcome to the Poetic Bytes Python Cheat Sheet — your one‑stop, no‑fluff reference for the Python programming language. Whether you're a beginner brushing up on fundamentals or an experienced developer looking for a quick syntax reminder, this page brings together the most essential concepts in a clean, executable format. Every code snippet is accompanied by an explanation that clarifies why the code is written that way, how it runs, what it produces, and where it fits into the bigger picture. You can copy any example with one click or run it live right in your browser (powered by Pyodide). Bookmark this page, share it with your peers, and keep coding with confidence.
📑 Table of Contents
Jump to any topic instantly
Variable Assignment & Dynamic Typing
How it operates: Values are assigned with
=. Multiple assignments and swapping are supported.Impact on output: The printed values show the current state of each variable.
Significance: This flexibility speeds up development and reduces boilerplate.
Python variables are dynamically typed. No type declaration needed.
name = "Glenn" age = 28 height = 1.75 is_student = True x, y, z = 10, 20, 30 a, b = 5, 10 a, b = b, a
Numeric Types
How it operates: Literals are interpreted directly; underscores improve readability. Type conversion functions (
int(), float()) are shown.Impact on output: The printed values demonstrate each numeric representation.
Significance: Understanding numeric types is crucial for math, data analysis, and scientific computing.
Integers, floats, and complex numbers with type conversion.
int_num = 42 float_num = 3.14159 complex_num = 3 + 4j big_num = 1_000_000 hex_num = 0xFF oct_num = 0o777 bin_num = 0b1010
String Methods & Operations
.strip(), .upper(), and slicing are essential.How it operates: Each method returns a new string (strings are immutable). Slicing uses
[start:stop:step].Impact on output: The transformed strings are printed, showing the effect of each operation.
Significance: Mastering string manipulation is key for text processing, formatting, and parsing.
Comprehensive string manipulation methods.
s = " Hello World " print(s.strip()) print(s.upper()) print(s.lower()) print(s.capitalize()) print(s.title()) print(s.replace("World", "Python")) print(s.split()) print("-".join(["a", "b", "c"])) print(s[0:5]) print(s[6:]) print(s[::-1])
Type Conversion Functions
How it operates: Built‑in functions like
int(), float(), str() attempt to convert the argument.Impact on output: The converted values are printed, showing the new type.
Significance: These functions are vital for handling user input and preparing data for processing.
Convert between Python data types.
int("42") float("3.14") str(42) bool(0) bool("") bool("hello") list((1, 2, 3)) tuple([1, 2, 3]) set([1, 2, 2, 3]) dict([("a", 1), ("b", 2)])
Constants & Special Values
None, True, False are fundamental to Python's logic and control flow.How it operates: They are singletons;
is checks identity. Ellipsis has uses in slicing and type hints.Impact on output: The boolean operations and identity checks show how these values behave.
Significance: Correct use of these constants is essential for conditionals and function returns.
Python's special constants and built-in values.
None True False NotImplemented Ellipsis print(None is None) print(True and False) print(Ellipsis)
Arithmetic Operators
How it operates:
+, -, *, / (float division), // (floor), % (modulo), ** (power).Impact on output: The results show the difference between true division and floor division.
Significance: These are the building blocks of any numeric computation.
Basic math operations with examples.
10 + 3 10 - 3 10 * 3 10 / 3 10 // 3 10 % 3 10 ** 3
Comparison Operators
How it operates: Return
True or False. Works on numbers, strings, and sequences.Impact on output: The booleans are printed, indicating the truth of each comparison.
Significance: They are the backbone of conditional logic.
Compare values with these operators.
5 == 5 5 != 3 5 < 10 5 > 3 5 <= 5 5 >= 3
Logical Operators
How it operates:
and, or, not return the last evaluated operand (short‑circuit).Impact on output: The printed results show the truth value of compound conditions.
Significance: Essential for complex conditionals and while loops.
Combine boolean conditions.
True and False True or False not True print(5 > 3 and 10 < 20) print(5 > 10 or 3 < 5)
Membership & Identity Operators
in) or compare object identity (is).How it operates:
in iterates through the container; is compares memory addresses.Impact on output: Prints booleans that indicate membership or identity.
Significance: Used for conditional checks and ensuring object equality vs. identity.
Check membership and object identity.
"apple" in ["apple", "banana"] "grape" not in ["apple", "banana"] "a" in "hello" 5 in range(10) x = [1, 2] y = x print(x is y)
Bitwise Operators
How it operates:
& (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).Impact on output: The results show the integer values after bitwise operations.
Significance: Essential for systems programming, networking, and embedded work.
Operate on bits of integers.
5 & 3 5 | 3 5 ^ 3 ~5 5 << 1 5 >> 1
If-Elif-Else Conditions
How it operates: Checks each condition in order; the first true branch executes. The ternary form
value if condition else other provides a compact alternative.Impact on output: The appropriate message or variable is assigned/printed.
Significance: Fundamental to all decision‑making in code.
Conditional execution with Python's indentation.
if condition: statement elif other_condition: statement else: statement result = "Pass" if score >= 70 else "Fail"
For Loops
How it operates:
for item in iterable assigns each item in turn. enumerate adds an index; zip pairs multiple iterables.Impact on output: Each iteration prints or processes the current element.
Significance: The most common loop for working with collections.
Iterate over sequences with for loops.
for item in iterable: print(item) for i, value in enumerate(items, start=1): print(i, value) for i in range(5): print(i)
While Loops
How it operates: The condition is evaluated before each iteration.
break exits early; continue skips to the next iteration.Impact on output: Prints values only for odd numbers (skipping evens) and stops when the break condition is met.
Significance: Essential for input validation, game loops, and indefinite iteration.
Loop while a condition remains true.
while condition: statement while True: if condition: break count = 0 while count < 10: count += 1 if count % 2 == 0: continue print(count)
Match Statement (Python 3.10+)
if-elif chains.How it operates: The
match expression is compared against patterns (literal values, variable captures, guards).Impact on output: Prints a message based on the value and its shape (e.g., a point tuple).
Significance: Enables concise and readable code for complex data structures.
Structural pattern matching with examples.
match value: case 0: print("Zero") case n if n > 0: print("Positive") case _: print("Other")
List Methods & Operations
How it operates: Methods like
append, insert, pop, remove, sort modify the list in place. List comprehensions build new lists concisely.Impact on output: The mutated list and new lists are printed, showing the transformations.
Significance: Lists are used everywhere; comprehension is a Pythonic way to create transformed lists.
Comprehensive list methods and comprehensions.
numbers = [1, 2, 3] numbers.append(4) numbers.insert(0, 0) value = numbers.pop() numbers.remove(2) numbers.sort() squares = [x**2 for x in range(5)] evens = [x for x in range(10) if x % 2 == 0]
Dictionary Methods & Operations
How it operates: Key assignment,
get (with default), pop, keys, values, items allow flexible manipulation. Dict comprehensions create new dicts.Impact on output: The modified dict and extracted values are printed.
Significance: Dictionaries are fundamental for data interchange (e.g., JSON), configuration, and caching.
Key-value store operations and comprehensions.
person = {"name": "Alice", "age": 30} person["city"] = "New York" name = person.get("name", "Unknown") age = person.pop("age") keys = person.keys() values = person.values() items = person.items() squares = {x: x**2 for x in range(5)}
Set Methods & Operations
How it operates:
add, discard, remove modify the set; union (|), intersection (&), difference (-), symmetric difference (^) perform set algebra.Impact on output: Prints the results of set operations and comprehensions.
Significance: Ideal for deduplication, membership checks, and relational data.
Set operations and methods for unique collections.
a = {1, 2, 3} b = {3, 4, 5} a.add(6) a.discard(2) a.remove(3) print(a | b) print(a & b) print(a - b) print(a ^ b) squares = {x**2 for x in range(5)}
Tuple & Unpacking
How it operates: Packing and unpacking allow clean assignment.
namedtuple adds field names for readability.Impact on output: The unpacked variables and the namedtuple are printed.
Significance: Tuples are memory‑efficient and safe from accidental modification.
Immutable sequences with powerful unpacking.
coords = (3, 4) x, y = coords first, *rest = [1, 2, 3, 4] single = (42,) from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point(3, 4) print(p.x, p.y)
Range & Slice Operations
range generates arithmetic progressions without storing all values; slicing extracts subsequences.How it operates:
range(start, stop, step); slicing syntax [start:stop:step] works on strings, lists, tuples.Impact on output: Prints the generated list and the sliced results.
Significance: Range is memory‑efficient for loops; slicing is a compact way to get sub‑sequences.
Generate sequences and slice collections.
range(10) range(2, 10) range(2, 10, 2) list(range(5)) s = [0, 1, 2, 3, 4, 5] s[1:4] s[::2] s[1::2] s[-1] s[-3:] s[:3]
Function Definition & Arguments
How it operates:
def defines a function; parameters can be positional, keyword, with default values, variable‑length (*args, **kwargs).Impact on output: The function returns and/or prints the result.
Significance: Functions are the fundamental building blocks of Python programs.
Define functions with various argument types.
def greet(name, greeting="Hello"): return f"{greeting}, {name}!" def sum_all(*args): return sum(args) def print_kwargs(**kwargs): for key, value in kwargs.items(): print(key, value)
Lambda Functions
map/filter.How it operates:
lambda arguments: expression. They are limited to a single expression.Impact on output: The results of applying lambdas through
map, filter, and sorted are printed.Significance: Lambdas enable functional‑style programming and reduce boilerplate.
Anonymous functions for quick operations.
square = lambda x: x**2 add = lambda a, b: a + b numbers = [1, 2, 3, 4] squared = list(map(lambda x: x**2, numbers)) evens = list(filter(lambda x: x % 2 == 0, numbers))
Decorators
How it operates: A decorator is a function that takes a function and returns a new function.
@wraps preserves metadata.Impact on output: The decorated function prints execution time before returning the result.
Significance: Decorators promote separation of concerns and code reuse.
Modify or extend function behaviour.
import time from functools import wraps def timer(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"Time: {end - start:.4f}s") return result return wrapper @timer def slow_function(): time.sleep(1) return "Done"
Closures
How it operates: The inner function captures variables from the outer scope;
nonlocal allows modification.Impact on output: The returned function retains the captured factor or counter state.
Significance: Enables functional programming patterns and callback creation.
Functions that remember their enclosing scope.
def make_multiplier(factor): def multiplier(x): return x * factor return multiplier double = make_multiplier(2) triple = make_multiplier(3) print(double(5)) print(triple(5)) def counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment
Class Definition & Methods
How it operates:
__init__ initialises attributes; methods have self as first parameter to access instance data.Impact on output: The car object’s state (odometer) updates with each drive, and the string representation is customised.
Significance: OOP is the paradigm for building scalable, maintainable systems.
Define classes with attributes and methods.
class Car: def __init__(self, make, model): self.make = make self.model = model self.odometer = 0 def drive(self, miles): self.odometer += miles return f"Driven {miles} miles" def __str__(self): return f"{self.make} {self.model}"
Inheritance & super()
How it operates: The child class overrides methods and can call parent methods with
super().Impact on output: Each animal produces its own sound, and the GoldenRetriever adds extra info.
Significance: Promotes code reuse and establishes hierarchical relationships.
Extend and override classes.
class Animal: def __init__(self, name): self.name = name def speak(self): pass class Dog(Animal): def speak(self): return f"{self.name} says Woof!" class Cat(Animal): def speak(self): return f"{self.name} says Meow!"
Property Decorators
How it operates:
@property defines a getter; @name.setter defines a setter that validates input.Impact on output: The name is retrieved and modified; an error is raised when an empty value is attempted.
Significance: Encapsulation without losing the simplicity of attribute access.
Getters, setters, and deleters.
class Person: def __init__(self, name): self._name = name @property def name(self): return self._name @name.setter def name(self, value): if not value: raise ValueError("Name cannot be empty") self._name = value
Dataclasses
__init__, __repr__, and more, reducing boilerplate.How it operates: The
@dataclass decorator adds special methods; field allows default factory. Frozen dataclasses are immutable.Impact on output: The auto‑generated repr shows all fields; properties like
is_adult are computed.Significance: Dataclasses are the modern, clean way to define data‑carrying classes.
Reduce boilerplate with dataclasses.
from dataclasses import dataclass, field @dataclass class Person: name: str age: int email: str = "" hobbies: list = field(default_factory=list) @property def is_adult(self) -> bool: return self.age >= 18
Class & Static Methods
How it operates:
@classmethod receives the class as first argument; @staticmethod receives no special first argument.Impact on output: The class method creates an instance; static methods compute results without instance state.
Significance: They provide alternative constructors and organise related functions.
Methods that work with the class itself.
class MathUtils: @staticmethod def add(a, b): return a + b @classmethod def from_string(cls, s): parts = s.split(",") return cls(int(parts[0]), int(parts[1]))
Generators & Yield
How it operates:
yield returns a value and pauses the function; the state is preserved for the next call.Impact on output: The Fibonacci numbers are generated on‑the‑fly and printed one by one.
Significance: Ideal for processing large files or streams without loading everything into memory.
Lazy iteration with generators.
def fibonacci(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b def read_large_file(path): with open(path, encoding="utf-8") as f: for line in f: yield line.strip()
Context Managers
How it operates: The
with statement calls __enter__ and __exit__; the contextlib decorator simplifies creation.Impact on output: The file is opened, written, and automatically closed, as shown by the print statements.
Significance: Prevents resource leaks and makes code robust.
Resource management with the with statement.
class ManagedFile: def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file: self.file.close()
Async/Await
How it operates:
async def defines a coroutine; await yields control to the event loop; asyncio.gather runs multiple tasks concurrently.Impact on output: The data from multiple APIs is fetched concurrently, reducing total wait time.
Significance: Crucial for web scraping, real‑time applications, and high‑performance servers.
Asynchronous programming for I/O-bound tasks.
import asyncio async def fetch_data(name, delay): await asyncio.sleep(delay) return f"Data from {name}" async def main(): results = await asyncio.gather( fetch_data("API 1", 1), fetch_data("API 2", 0.5), fetch_data("API 3", 1.5) ) for result in results: print(result)
Type Hints & Generics
How it operates: Annotations specify expected types; generics (
TypeVar) allow parameterised types.Impact on output: The functions still run as normal, but the types are now documented.
Significance: Helps catch bugs early and facilitates collaboration on larger projects.
Add type information for better tooling.
from typing import List, Dict, Optional, TypeVar, Generic T = TypeVar("T") def greet(name: str) -> str: return f"Hello, {name}" def find_user(id: int) -> Optional[Dict[str, str]]: return {"name": "Alice"} def process(items: List[int]) -> List[int]: return [i * 2 for i in items]
Descriptors
How it operates:
__set_name__, __get__, __set__ manage the attribute. This example enforces positive values.Impact on output: The price and quantity are set; an error is raised when a negative value is assigned.
Significance: Provides a powerful mechanism for data validation, ORMs, and framework internals.
Control attribute access in classes.
class PositiveNumber: def __set_name__(self, owner, name): self.name = name def __get__(self, obj, objtype=None): if obj is None: return self return obj.__dict__.get(self.name, 0) def __set__(self, obj, value): if value < 0: raise ValueError("Must be positive") obj.__dict__[self.name] = value
File Operations
How it operates:
open() with modes 'r', 'w', 'a'; using with ensures the file is closed automatically.Impact on output: The file is created/overwritten/appended, and its content is printed.
Significance: Fundamental for any application that needs to store or read data.
Read, write, and append files.
with open("file.txt", "r") as f: content = f.read() with open("file.txt", "w") as f: f.write("Hello") with open("file.txt", "a") as f: f.write("New line")
JSON Handling
How it operates:
json.dumps serialises Python objects to JSON strings; json.loads parses JSON back to Python.Impact on output: The formatted JSON string is printed, then the parsed data is accessed.
Significance: Enables seamless data exchange between Python and other systems.
Encode and decode JSON data.
import json data = {"name": "Alice", "age": 30} json_str = json.dumps(data, indent=2) parsed = json.loads(json_str)
Exception Handling
How it operates:
try block contains risky code; except catches specific exceptions; else runs if no exception; finally always runs.Impact on output: The division result or error message is printed; cleanup is performed.
Significance: Makes applications robust and user‑friendly.
Graceful error handling with try/except.
try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except ValueError: print("Invalid value") else: print("Success") finally: print("Cleanup")
Custom Exceptions
How it operates: Inherit from
Exception (or a subclass), add attributes like code or field.Impact on output: The custom exception is raised and caught, printing the error code and message.
Significance: Improves error handling by providing context that is specific to your application.
Create your own exception classes.
class CustomError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code
print() – Output to consolelen() – Length of sequencetype() – Type of objectint() – Convert to intfloat() – Convert to floatstr() – Convert to stringlist() – Convert to listdict() – Create dictset() – Create settuple() – Convert to tuplesum() – Sum iterablemax() – Maximum valuemin() – Minimum valuesorted() – Sorted listenumerate() – Index-value pairszip() – Zip iterablesany() – Check if any truthyall() – Check if all truthyfilter() – Filter iterablemap() – Map functionrange() – Generate rangeinput() – Read inputisinstance() – Type checkabs() – Absolute valueround() – Round numberopen() – Open filehelp() – Get helpdir() – List attributesid() – Object identityhash() – Hash valuebool() – Convert to booleaniter() – Get iteratornext() – Next itemreversed() – Reverse iterablechr() – Unicode characterord() – Unicode code pointEssential Modules
math– Mathematical functionsrandom– Random number generationdatetime– Date and timejson– JSON encoding/decodingcsv– CSV file handlingre– Regular expressionsitertools– Iterator toolscollections– Specialized containersfunctools– Higher-order functionsos– Operating system interfacesys– System-specific parameterspathlib– Object-oriented path handlingargparse– Command-line parsinglogging– Logging frameworkhashlib– Cryptographic hashingsubprocess– Run external commands
collections & itertools
Counter– Count hashable objectsdefaultdict– Missing keys defaultdeque– Double-ended queueOrderedDict– Maintains insertion ordernamedtuple– Tuples with named fieldschain()– Chain iterablesgroupby()– Group consecutive itemscombinations()– All combinationspermutations()– All permutationsproduct()– Cartesian productislice()– Slice iteratorcount()– Infinite countercycle()– Infinite cyclerepeat()– Repeat value
Binary Search
How it operates: Repeatedly divides the search interval in half, comparing the target with the middle element.
Impact on output: Returns the index of the target or -1 if not found, printed for each search.
Significance: Classic algorithm used in many libraries and problem‑solving.
Efficient search in sorted arrays.
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1
Quicksort
How it operates: Pick a pivot, partition the array into elements less than, equal to, and greater than the pivot, then recursively sort the sub‑arrays.
Impact on output: The unsorted list is transformed into a sorted list, printed side‑by‑side.
Significance: Widely used in practice; demonstrates the divide‑and‑conquer approach.
Efficient divide-and-conquer sorting algorithm.
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right)
Factorial & Recursion
How it operates: The base case stops recursion;
lru_cache memoizes results to avoid repeated calculations.Impact on output: The factorial and Fibonacci numbers are computed and printed for a range of inputs.
Significance: Recursion simplifies problems that can be broken into smaller, identical sub‑problems.
Classic recursive examples with memoization.
def factorial(n): if n <= 1: return 1 return n * factorial(n - 1) from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)
pytest Basics
How it operates: Write functions prefixed with
test_ and use assert to verify outcomes.Impact on output: When run, pytest reports whether tests pass or fail; here we simulate a successful run.
Significance: Automated testing is essential for maintaining code quality.
Write and run tests with pytest.
def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 assert add(-1, 1) == 0
unittest Basics
How it operates: Define a subclass of
TestCase and write methods starting with test_; use assertion methods like assertEqual.Impact on output: The test runner executes all tests and reports success or failure.
Significance: Provides a solid foundation for writing unit tests without external dependencies.
Python's built-in testing framework.
import unittest class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(2 + 3, 5) def test_positive(self): self.assertTrue(5 > 0)
🎯 Final words — This cheat sheet is designed to be your go‑to reference for Python programming. Each snippet has been carefully chosen to illustrate a core concept, with explanations that connect the why and how behind the code. Use it to refresh your memory, learn new patterns, or share it with your fellow developers. Remember, coding is not just about writing syntax — it's about solving problems with clarity and efficiency. Keep this page close, and happy coding!