Skip to main content

Python Cheatsheet

This cheatsheet focuses on quick reminders of Python-specific syntax and concepts for experienced developers.

Standard Library

Built in Types

List/Sequences & Dictionaries(Hashmaps)​

Sequence Types (List, Tuple, Range)​

Mapping Types​

  • Dictionaries/Hashmaps

    • Scroll down the docs for quick shorthand, e.g. in, not in as well as everything that exists on the Dict class def.
  • Newer versions of python preserve/have insert order, which means you can do things like: pop, reverse, etc.

Creating Dictionaries​

Dictionaries can be created by several means:

  • Use a comma-separated list of key: value pairs within braces: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}
  • Use a dict comprehension: {}, {x: x ** 2 for x in range(10)}
  • Use the type constructor: dict(), dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200)

More​

Remember to refer to Built in Types. It's an excellent reference. For literally most everything you might do: strings, bytes, Sets, Unions, Generics, etc.

🧠 Commonly Forgotten Language Basics​

  • List Comprehension:

    squares = [x*x for x in range(10) if x % 2 == 0]
  • Lambda Functions:

    add = lambda x, y: x + y
  • Ternary Operator:

    result = "yes" if x > 0 else "no"
  • Unpacking:

    a, b, *rest = [1, 2, 3, 4, 5]  # rest = [3, 4, 5]

πŸ” Loops & Iterators​

Enumerate:

  • in is the only keyword for looping
  • Use range to do a trad loop: for loopVar; condtion; inc/dec
    for i in range(start, stop, step):
Typefor x in ... yieldsNotes
listelementsfor x in [1, 2] β†’ x = 1, then x = 2
tupleelementsfor x in (1, 2) β†’ x = 1, then x = 2
setelementsOrder is not guaranteed
strcharactersfor c in "abc" β†’ c = "a", etc.
dictkeysfor k in {"a": 1} β†’ k = "a"
dict.items()(key, value) tuplesfor k, v in dict.items() β†’ both key and value
enumerate()(index, value) tuplesUse with sequences: for i, x in enumerate(arr)
zip()tuples from multiple iterablesfor a, b in zip(list1, list2) β†’ parallel unpacking
custom iterablewhatever its __iter__() yieldsYou control what’s yielded

Zip:

for name, score in zip(names, scores):
print(name, score)

Some Handy Built in Functions

Any / All:

any([False, True])  # True
all([True, True]) # True

Full list of Built in Functions


Error Handling / Safety​

  • with Statement (Context Manager):

    with open('file.txt') as f:
    data = f.read()
  • Try/Except/Else/Finally:

    try:
    ...
    except ValueError:
    ...
    else:
    ...
    finally:
    ...
  • Finally will always* run, even if the except block is hit.

    • Unless os.exit(), kill -9, power loss, etc.

Intellisense​

  • Type/Function Annotations (IntelliSense):

    def greet(name: str) -> str:
    return f"Hello {name}"
  • Docstring for IntelliSense:

    def foo(x: int) -> int:
    """Doubles the input value."""
    return x * 2

πŸ” Reflection & Meta​

  • Type Checking:

    isinstance(x, int)
  • Dynamic Attributes:

    hasattr(obj, 'attr')
    getattr(obj, 'attr', default)
    setattr(obj, 'attr', value)
  • Introspection:

    dir(obj)
    type(obj)
    vars(obj)

🧱 No Block Scope​

  • Variables inside if, for, etc. leak into the outer scope.

🧡 Syntactic Sugar​

  • f-Strings:

    name = "Alice"
    print(f"Hello, {name}")
  • Walrus Operator (3.8+):

    if (n := len(my_list)) > 10:
    print(f"List too long ({n} items)")
  • Underscore Usage:

    _, val = (1, 2)  # Discard value

πŸ§ͺ Comprehensions​

  • Set and Dict Comprehensions:
    squares = {x*x for x in range(5)}
    squared_map = {x: x*x for x in range(5)}

🧬 Special Methods (Dunder)​

  • __init__, __str__, __repr__, __eq__, __len__, etc.
    class Thing:
    def __init__(self, name): self.name = name
    def __repr__(self): return f"Thing({self.name})"

⚠️ Common Gotchas​

  • Default args are evaluated once:

    def bad(x=[]): ...
  • Strings are immutable; lists are not.

  • No block scope (again, for emphasis).

  • None, 0, "", [], {} all evaluate as False.