Python Articles - Python Morsels

16 min read Original article ↗

Cheat Sheets

13 articles 4 screencasts · 2 hr 21 min read 17 min watch

A collection of the many Python cheat sheets within Python Morsels articles and screencasts.

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

23 articles 18 screencasts · 1 hr 42 min read 56 min watch

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

12 articles 11 screencasts · 45 min read 30 min watch

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

24 articles 18 screencasts · 1 hr 42 min read 1 hr 2 min watch

These articles are all about Python's core structures: lists, tuples, sets, and dictionaries.

Looping

16 articles 14 screencasts · 56 min read 40 min watch

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.

Debugging

8 articles 5 screencasts · 51 min read 18 min watch

Your code has a bug in it. What now?

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

10 articles 9 screencasts · 45 min read 34 min watch

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

18 articles 16 screencasts · 1 hr 12 min read 53 min watch

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.

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

18 articles 17 screencasts · 1 hr 18 min read 58 min watch

Reading from and writing to text files (and sometimes binary files) is an important skill for most Python programmers.

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.

These topics are commonly overlooked by new Python programmers.

Exceptions

10 articles 8 screencasts · 56 min read 28 min watch

Exceptions happens! When exceptions happen, how should interpret the traceback for an exception? And how, when, and where should you catch exceptions?

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

3 articles 0 screencasts · 12 min read 0 min watch

Working with dates and times in Python

Asterisks

7 articles 7 screencasts · 21 min read 21 min watch

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.

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

21 articles 18 screencasts · 1 hr 19 min read 1 hr 7 min watch

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

6 articles 4 screencasts · 31 min read 14 min watch

Inheritance

3 articles 3 screencasts · 11 min read 10 min watch

Classes can inherit functionality from other classes in Python. Class inheritance can be helpful, but it can also be very complex.

Properties

4 articles 4 screencasts · 14 min read 13 min watch

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

22 articles 14 screencasts · 1 hr 58 min read 48 min watch

You can overload many operators, protocols, and bits of functionality on your Python objects by implementing dunder methods.

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 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.

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

14 articles 14 screencasts · 54 min read 48 min watch

Decorators are functions that accept functions and return functions. They're weird but powerful.

Other

19 articles 10 screencasts · 1 hr 22 min read 40 min watch

No matches

Try clearing your search or removing the topic filter.

2026

  1. Stacks and queues New
  2. Selecting random values New
  3. What types of exceptions should you catch? New
  4. The list extend method New
  5. Assigning to slices
  6. Standard error
  7. Making friendly classes
  8. Invent your own comprehensions
  9. When are classes used in Python?
  10. Lexicographical ordering
  11. Setting default dictionary values
  12. switch-case in Python? It's not match-case!
  13. Is it a class or a function?
  14. All iteration is the same
  15. Self-concatenation
  16. Debugging with f-strings
  17. Implicit string concatenation

2025

  1. Embrace whitespace
  2. Wrapping text output
  3. Unnecessary parentheses
  4. __slots__ for optimizing classes
  5. __dict__: where Python stores attributes
  6. T-strings: Python's Fifth String Formatting Technique?
  7. Python 3.14's best new features
  8. Why splitlines() instead of split("\n")?
  9. Nested list comprehensions
  10. Python REPL Shortcuts & Features
  11. Removing list items
  12. The power of Python's print function
  13. Checking your operating system
  14. Checking for string prefixes and suffixes
  15. Re-raising exceptions
  16. Using dictionaries
  17. Nested functions
  18. Don't call dunder methods
  19. Decorators with optional arguments
  20. Breaking out of a loop
  21. Python's "while" loop
  22. Equality with data structures
  23. Decorators can return anything
  24. Avoid indexes
  25. Enclosing scope
  26. Looping in reverse
  27. Common decorators included with Python
  28. Sorting iterables
  29. Practical uses of sets
  30. Mutable default arguments
  31. Unpacking arbitrary keyword arguments into a function call
  32. Checking whether iterables are equal
  33. Refactoring long boolean expressions
  34. Alternatives to Python's "break" statement
  35. Running subprocesses
  36. The features of Python's help() function
  37. Multiline strings
  38. Avoid over-commenting
  39. Newlines and escape sequences
  40. Python Terminology: an unofficial glossary
  41. datetime arithmetic
  42. Uppercasing and lowercasing
  43. Python's range() function
  44. The benefits of trailing commas

2024

  1. Merging dictionaries
  2. Storing attributes on functions
  3. Python's pathlib module
  4. Inspecting objects
  5. Customizing dataclass fields
  6. Customizing dataclass initialization
  7. Python 3.13's best new features
  8. Converting a string to a datetime
  9. The string split method
  10. Prompting a user for input
  11. Understanding help()
  12. Boolean operators
  13. Commenting
  14. Creating Python programs
  15. Functions and Methods
  16. Arithmetic
  17. Checking for an empty list
  18. Customizing dataclasses with arguments
  19. What are dataclasses?
  20. How to make a tuple
  21. Using "else" in a comprehension
  22. What are lists in Python?
  23. Strings
  24. Python's getattr function
  25. Data structures contain pointers
  26. Python's __setattr__ method
  27. Python's many command-line utilities
  28. Equality versus identity
  29. Assignment vs. Mutation
  30. Supporting containment checks
  31. Variables are pointers
  32. Overloading all attribute lookups: __getattribute__ versus __getattr__
  33. Multiline comments
  34. Python Big O: the time complexities of different data structures
  35. Python's http.server module
  36. Unnecessary else statements
  37. Every dunder method
  38. List slicing
  39. The contextmanager decorator
  40. Arithmetic Dunder Methods
  41. The list insert method
  42. TextIOWrapper‽ converting files to strings
  43. None
  44. Goose typing
  45. Using the Python REPL

2023

  1. Chained comparisons
  2. zip with different length iterables
  3. Descriptors
  4. Inspect modules interactively
  5. Working with JSON data
  6. Solving programming exercises
  7. Booleans are integers
  8. Reading from standard input
  9. Python's lambda functions
  10. What are metaclasses?
  11. Python's assert statement
  12. Are dictionaries ordered in Python?
  13. What is recursion?
  14. Python's range is a lazy sequence
  15. Using "else" with a loop
  16. Reserved words
  17. Creating a context manager
  18. Using attributes on classes
  19. Python's next() function
  20. The difference between return and print
  21. Django June 2023: Tips & Discussions
  22. Counting occurrences in Python with collections.Counter
  23. Fixing circular imports
  24. Substrings in Python: checking if a string contains another string
  25. How to assign a variable
  26. Short-circuit evaluation
  27. Dynamically importing modules
  28. How to make a sequence
  29. Python's any() and all() functions
  30. Implementing slicing
  31. What is a context manager?
  32. Function overloading
  33. Remove duplicates from a list
  34. Looping over dictionaries
  35. What is a mapping?
  36. Python's list constructor: when and how to use it
  37. Writing a CSV file
  38. Conditional operators
  39. Reading a CSV file
  40. Removing a dictionary key
  41. Singletons

2022

  1. Python's "if" statement
  2. Dynamically evaluating code
  3. List containment checks
  4. Python's ternary operator
  5. breakpoint: debugging
  6. SyntaxError: invalid syntax
  7. How does file buffering work?
  8. What does // mean in Python?
  9. Unindent multiline strings in Python with dedent
  10. Installing Python packages with pip
  11. Fixing TypeError: can only concatenate str (not "int") to str
  12. reduce() in Python and why to avoid it
  13. Creating a mapping
  14. What's __init__.py?
  15. Python's String Methods
  16. How not to use super
  17. When should you call super?
  18. Title-case a String
  19. Using pip requirements files
  20. Using virtual environments
  21. When to use NotImplemented
  22. How I made a dataclass remover
  23. Appreciating Python's match-case by parsing Python code
  24. Python's setattr function and __setattr__ method
  25. When is equality the same as identity?
  26. Catching all exceptions
  27. Callables: Python's "functions" are sometimes classes
  28. Seeking in files
  29. Reading binary files
  30. File modes
  31. Flatten a list of lists
  32. Making hashable objects
  33. Unicode character encodings
  34. What is "hashable" in Python?
  35. Python f-string tips & cheat sheets
  36. Static methods
  37. Class methods
  38. How to make an iterator
  39. How to make an iterable
  40. What is an iterator?
  41. Built-in Functions
  42. How to create a generator function
  43. Variables and objects
  44. What is a generator function?
  45. Exiting a Python program
  46. Dunder variables
  47. Making the len function work on your Python objects
  48. Supporting index and key lookups
  49. How to remove spaces
  50. Catching multiple exception types
  51. What can you do with exception objects?
  52. How to raise an exception
  53. Python's try-except blocks
  54. dataclasses
  55. Deciphering Python's Traceback (most recent call last)

2021

  1. Representing binary data with bytes
  2. Converting datetime to UTC
  3. Overloading equality
  4. Making a lazy attribute
  5. Locally testing Python Morsels exercises
  6. Convert a list to a string
  7. Positional-only function arguments
  8. Unpacking iterables into iterables
  9. Unpacking iterables into function arguments
  10. Extended iterable unpacking
  11. Importing everything from a module
  12. Modules are cached
  13. File-like objects
  14. Printing to a file
  15. Write to a file
  16. Files are iterators
  17. Read a file line-by-line
  18. How to read from a text file
  19. Defining a main function
  20. Tuple unpacking isn't just for tuples
  21. Importing a module runs code
  22. Decorators aren't always functions
  23. Parsing command-line arguments
  24. Making a class decorator
  25. Accessing command-line arguments
  26. Python's walrus operator
  27. Raw strings
  28. Customizing what happens when you assign an attribute
  29. Making a read-only attribute
  30. What can you do with generator expressions?
  31. Python's map and filter functions
  32. Generators are iterators
  33. Turning a list comprehension into a generator expression
  34. How to write a generator expression
  35. Augmented assignments mutate
  36. Mutable tuples
  37. Making a decorator that accepts arguments
  38. Module versus Script
  39. Making a well-behaved decorator
  40. How to make a decorator
  41. What is a decorator?
  42. Passing functions as arguments to other functions
  43. The meaning of "callable"
  44. Mutating with an assignment statement
  45. When should you not use a list comprehension?
  46. Turning a for loop into a list comprehension
  47. Why use a list comprehension?
  48. Breaking up long lines of code
  49. Where does Python look for methods?
  50. Set and dictionary comprehensions
  51. List comprehensions
  52. 4 ways to import a module
  53. Making an auto-updating attribute
  54. The assignments hiding in your functions
  55. Does Python have constants?
  56. How attribute lookups and assignments work
  57. Truthiness
  58. Deep tuple unpacking
  59. Tuple unpacking
  60. Importing a module
  61. Assignment isn't just about the equals sign
  62. Inheriting one class from another
  63. Methods are just functions attached to classes
  64. Everything is an object
  65. Pass: Python's no-op
  66. Docstrings
  67. Attributes are everywhere
  68. What is __init__ in Python?
  69. Each module has its own global scope
  70. Scope is about assignment, not mutation
  71. String concatenation vs string interpolation
  72. Assigning to global variables
  73. Local and global variables
  74. Customizing the string representation of your objects
  75. Dunder methods

2020

  1. Python's 2 different string representations
  2. Python's self
  3. Classes are everywhere
  4. What is a class?
  5. Accepting arbitrary keyword arguments
  6. Keyword-only function arguments
  7. Sequences
  8. Accepting any number of arguments to a function
  9. How to make a function
  10. Positional vs keyword arguments
  11. How to call a function
  12. Python doesn't have type coercion
  13. Python's zip function
  14. Looping with indexes
  15. What is an iterable?
  16. Python's "for" loop
  17. String Representations for Classes
  18. Duck Typing
  19. The Iterator Protocol
  20. Zipping an Iterator to Itself

No matches

Try clearing your search or removing the topic filter.