Cheat Sheets
A collection of the many Python cheat sheets within Python Morsels articles and screencasts.
Assignment and Mutation
Python's variables aren't buckets that contain things; they're pointers that reference objects.
The way Python's variables work can often confuse folks new to Python, both new programmers and folks moving from other languages like C++ or Java.
Strings
Regardless of what you're doing in Python, you almost certainly use strings all the time. A string is usually the default tool we reach for when we don't have a more specific way to represent our data.
Conditionals
Conditionals statements (if statements) are useful for making a branch in our Python code. If a particular condition is met, we run one block of code, and if not then we run another block.
Data Structures
These articles are all about Python's core structures: lists, tuples, sets, and dictionaries.
Looping
Unlike JavaScript, C, Java, and many other programming languages, we don't have traditional C-style for loops.
Our for loops in Python don't have indexes.
This small distinction makes for some big differences in the way we loop in Python.
Comments
Comments and documentation strings
Debugging
Your code has a bug in it. What now?
Tuple Unpacking
It's tempting to reach for indexes when working with tuples, lists, and other sequences, but if we know the shape of the tuple we're working with, we can unpack it instead.
Tuple unpacking (aka "multiple assignment" or "iterable unpacking") is often underutilized by new Python programmers.
Modules
Modules are the tool we use for breaking up our code into multiple files in Python.
When you write a .py file, you're making a Python module.
You can import your own modules, modules included in the Python standard library, or modules in third-party packages.
Functions
Python, like many programming languages, has functions. A function is a block of code you can call to run that code.
Python's functions have a lot of "wait I didn't know that" features. Functions can define default argument values, functions can be called with keyword arguments, and functions can be written to accept any number of arguments.
Variable Scope
Python has 4 scopes: local, enclosing, global, and built-ins. Python's "global" variables are only global to the module they're in. The only truly universal variables are the built-ins.
Files
Reading from and writing to text files (and sometimes binary files) is an important skill for most Python programmers.
Command-Line Progarms
A .py file can be used as a module or as a "script" which is run from your operating system's command-line/terminal. Python is a great programming language for making command-line scripts.
Overlooked Fundamentals
These topics are commonly overlooked by new Python programmers.
Exceptions
Exceptions happens! When exceptions happen, how should interpret the traceback for an exception? And how, when, and where should you catch exceptions?
Comprehensions
In Python it's very common to build up new lists while looping over old lists. Partly this is because we don't mutate lists very often while looping over them.
Because we build up new lists from old ones so often, Python has a special syntax to help us with this very common operation: list comprehensions.
datetime
Working with dates and times in Python
Asterisks
Python has an * prefix operator and a ** prefix operator that can be used in many different ways.
The below screencasts & articles explain each of the many uses of the * and ** operators in Python.
Package Management
Python's standard library includes a lot of helpful modules. But often Python code depends on third-party packages. What are the best practices when working with third party packages in Python?
Classes
Classes are a way to bundle functionality and state together.
The terms "type" and "class" are interchangeable: list, dict, tuple, int, str, set, and bool are all classes.
You'll certainly use quite a few classes in Python (remember types are classes) but you may not need to create your own often.
Data Classes
Inheritance
Classes can inherit functionality from other classes in Python. Class inheritance can be helpful, but it can also be very complex.
Properties
We don't use getter and setter methods in Python. Instead we make properties.
Properties allow us to customize what happens when you access an attribute and what happens when you assign to an attribute.
Dunder Methods
You can overload many operators, protocols, and bits of functionality on your Python objects by implementing dunder methods.
Generator Expressions
List comprehensions make new lists. Generator expressions make new generator objects. Generators are iterators, which are lazy single-use iterables. Unlike lists, generators aren't data structures. Instead they do work as you loop over them.
Generator Functions
Generator functions look like regular functions but they have one or more yield statements within them. Unlike regular functions, the code within a generator function isn't run when you call it! Calling a generator function returns a generator object, which is a lazy iterable.
Context Managers
A context manager as an object that can be used with Python's with blocks. You can make your own context manager by implementing a __enter__ method and a __exit__ method.
Decorators
Decorators are functions that accept functions and return functions. They're weird but powerful.
Other
No matches
Try clearing your search or removing the topic filter.
2026
- Selecting random values New
- What types of exceptions should you catch? New
- The list extend method New
- Assigning to slices New
- Standard error New
- Making friendly classes New
- Invent your own comprehensions New
- When are classes used in Python? New
- Lexicographical ordering
- Setting default dictionary values
- switch-case in Python? It's not match-case!
- Is it a class or a function?
- All iteration is the same
- Self-concatenation
- Debugging with f-strings
- Implicit string concatenation
2025
- Embrace whitespace
- Wrapping text output
- Unnecessary parentheses
- __slots__ for optimizing classes
- __dict__: where Python stores attributes
- T-strings: Python's Fifth String Formatting Technique?
- Python 3.14's best new features
- Why splitlines() instead of split("\n")?
- Nested list comprehensions
- Python REPL Shortcuts & Features
- Removing list items
- The power of Python's print function
- Checking your operating system
- Checking for string prefixes and suffixes
- Re-raising exceptions
- Using dictionaries
- Nested functions
- Don't call dunder methods
- Decorators with optional arguments
- Breaking out of a loop
- Python's "while" loop
- Equality with data structures
- Decorators can return anything
- Avoid indexes
- Enclosing scope
- Looping in reverse
- Common decorators included with Python
- Sorting iterables
- Practical uses of sets
- Mutable default arguments
- Unpacking arbitrary keyword arguments into a function call
- Checking whether iterables are equal
- Refactoring long boolean expressions
- Alternatives to Python's "break" statement
- Running subprocesses
- The features of Python's help() function
- Multiline strings
- Avoid over-commenting
- Newlines and escape sequences
- Python Terminology: an unofficial glossary
- datetime arithmetic
- Uppercasing and lowercasing
- Python's range() function
- The benefits of trailing commas
2024
- Merging dictionaries
- Storing attributes on functions
- Python's pathlib module
- Inspecting objects
- Customizing dataclass fields
- Customizing dataclass initialization
- Python 3.13's best new features
- Converting a string to a datetime
- The string split method
- Prompting a user for input
- Understanding help()
- Boolean operators
- Commenting
- Creating Python programs
- Functions and Methods
- Arithmetic
- Checking for an empty list
- Customizing dataclasses with arguments
- What are dataclasses?
- How to make a tuple
- Using "else" in a comprehension
- What are lists in Python?
- Strings
- Python's getattr function
- Data structures contain pointers
- Python's __setattr__ method
- Python's many command-line utilities
- Equality versus identity
- Assignment vs. Mutation
- Supporting containment checks
- Variables are pointers
- Overloading all attribute lookups: __getattribute__ versus __getattr__
- Multiline comments
- Python Big O: the time complexities of different data structures
- Python's http.server module
- Unnecessary else statements
- Every dunder method
- List slicing
- The contextmanager decorator
- Arithmetic Dunder Methods
- The list insert method
- TextIOWrapper‽ converting files to strings
- None
- Goose typing
- Using the Python REPL
2023
- Chained comparisons
- zip with different length iterables
- Descriptors
- Inspect modules interactively
- Working with JSON data
- Solving programming exercises
- Booleans are integers
- Reading from standard input
- Python's lambda functions
- What are metaclasses?
- Python's assert statement
- Are dictionaries ordered in Python?
- What is recursion?
- Python's range is a lazy sequence
- Using "else" with a loop
- Reserved words
- Creating a context manager
- Using attributes on classes
- Python's next() function
- The difference between return and print
- Django June 2023: Tips & Discussions
- Counting occurrences in Python with collections.Counter
- Fixing circular imports
- Substrings in Python: checking if a string contains another string
- How to assign a variable
- Short-circuit evaluation
- Dynamically importing modules
- How to make a sequence
- Python's any() and all() functions
- Implementing slicing
- What is a context manager?
- Function overloading
- Remove duplicates from a list
- Looping over dictionaries
- What is a mapping?
- Python's list constructor: when and how to use it
- Writing a CSV file
- Conditional operators
- Reading a CSV file
- Removing a dictionary key
- Singletons
2022
- Python's "if" statement
- Dynamically evaluating code
- List containment checks
- Python's ternary operator
- breakpoint: debugging
- SyntaxError: invalid syntax
- How does file buffering work?
- What does // mean in Python?
- Unindent multiline strings in Python with dedent
- Installing Python packages with pip
- Fixing TypeError: can only concatenate str (not "int") to str
- reduce() in Python and why to avoid it
- Creating a mapping
- What's __init__.py?
- Python's String Methods
- How not to use super
- When should you call super?
- Title-case a String
- Using pip requirements files
- Using virtual environments
- When to use NotImplemented
- How I made a dataclass remover
- Appreciating Python's match-case by parsing Python code
- Python's setattr function and __setattr__ method
- When is equality the same as identity?
- Catching all exceptions
- Callables: Python's "functions" are sometimes classes
- Seeking in files
- Reading binary files
- File modes
- Flatten a list of lists
- Making hashable objects
- Unicode character encodings
- What is "hashable" in Python?
- Python f-string tips & cheat sheets
- Static methods
- Class methods
- How to make an iterator
- How to make an iterable
- What is an iterator?
- Built-in Functions
- How to create a generator function
- Variables and objects
- What is a generator function?
- Exiting a Python program
- Dunder variables
- Making the len function work on your Python objects
- Supporting index and key lookups
- How to remove spaces
- Catching multiple exception types
- What can you do with exception objects?
- How to raise an exception
- Python's try-except blocks
- dataclasses
- Deciphering Python's Traceback (most recent call last)
2021
- Representing binary data with bytes
- Converting datetime to UTC
- Overloading equality
- Making a lazy attribute
- Locally testing Python Morsels exercises
- Convert a list to a string
- Positional-only function arguments
- Unpacking iterables into iterables
- Unpacking iterables into function arguments
- Extended iterable unpacking
- Importing everything from a module
- Modules are cached
- File-like objects
- Printing to a file
- Write to a file
- Files are iterators
- Read a file line-by-line
- How to read from a text file
- Defining a main function
- Tuple unpacking isn't just for tuples
- Importing a module runs code
- Decorators aren't always functions
- Parsing command-line arguments
- Making a class decorator
- Accessing command-line arguments
- Python's walrus operator
- Raw strings
- Customizing what happens when you assign an attribute
- Making a read-only attribute
- What can you do with generator expressions?
- Python's map and filter functions
- Generators are iterators
- Turning a list comprehension into a generator expression
- How to write a generator expression
- Augmented assignments mutate
- Mutable tuples
- Making a decorator that accepts arguments
- Module versus Script
- Making a well-behaved decorator
- How to make a decorator
- What is a decorator?
- Passing functions as arguments to other functions
- The meaning of "callable"
- Mutating with an assignment statement
- When should you not use a list comprehension?
- Turning a for loop into a list comprehension
- Why use a list comprehension?
- Breaking up long lines of code
- Where does Python look for methods?
- Set and dictionary comprehensions
- List comprehensions
- 4 ways to import a module
- Making an auto-updating attribute
- The assignments hiding in your functions
- Does Python have constants?
- How attribute lookups and assignments work
- Truthiness
- Deep tuple unpacking
- Tuple unpacking
- Importing a module
- Assignment isn't just about the equals sign
- Inheriting one class from another
- Methods are just functions attached to classes
- Everything is an object
- Pass: Python's no-op
- Docstrings
- Attributes are everywhere
- What is __init__ in Python?
- Each module has its own global scope
- Scope is about assignment, not mutation
- String concatenation vs string interpolation
- Assigning to global variables
- Local and global variables
- Customizing the string representation of your objects
- Dunder methods
2020
- Python's 2 different string representations
- Python's self
- Classes are everywhere
- What is a class?
- Accepting arbitrary keyword arguments
- Keyword-only function arguments
- Sequences
- Accepting any number of arguments to a function
- How to make a function
- Positional vs keyword arguments
- How to call a function
- Python doesn't have type coercion
- Python's zip function
- Looping with indexes
- What is an iterable?
- Python's "for" loop
- String Representations for Classes
- Duck Typing
- The Iterator Protocol
- Zipping an Iterator to Itself
No matches
Try clearing your search or removing the topic filter.