Skip to content

Instantly share code, notes, and snippets.

@stefanthoss
Last active July 11, 2025 20:26
Show Gist options
  • Save stefanthoss/cfb03674c0ea46aa6e05af884e29628e to your computer and use it in GitHub Desktop.
Save stefanthoss/cfb03674c0ea46aa6e05af884e29628e to your computer and use it in GitHub Desktop.
Python Cheat Sheet

Dictionaries

  • d.items() returns an iterable with key-value pairs as tuples
  • d.keys() returns an iterable with all keys
  • d.values() returns an iterable with all values
  • dict(sorted(d.items())) returns a dict sorted by keys
  • dict(sorted(d.items(), key=lambda x: x[1])) returns a dict sorted by values
  • d.get(key, default=None) returns the value for a key
  • d.pop(key, default=None) removes the key and returns the value for key
  • d.popitem() removes the last item added and returns it as (key, value) (LIFO)

Flow Control

  • break: Terminate the current loop.
  • continue: Skip the current iteration of a loop and move to the next iteration.
  • pass: Do nothing.

Iterables

  • i.all() returns True if all items are True
  • i.any() returns True if any item is True
  • i.min() returns smallest item
  • i.max() returns largest item
  • i.sum() returns sum of all items
  • reversed(i) returns the reverse
sorted(list)
sorted(list, reverse=True)
sorted(string_list, key=str.lower)  # Sort by lower case
sorted(string_list, key=int)        # Sort by casted integer
for i, el in enumerate(list):
  print(i, el)  ## i = index, el = element

Merge 2+ lists into one list containing tuples of mapped items:

list(zip(i1, i2, ...))              #  length = shorted list

from itertools import zip_longest
zip_longest(i1, i2, fillvalue="?")  # length = longest list, filled with "?"

List Comprehension

[expression for item in iterable if condition]
[expression if condition else other_expression for item in iterable]

Filter a list with [x for x in iterable if condition].

List Misc

  • list.extend(iterable) extends the list by appending all items
  • list.insert(i, x) inserts x at position i
  • list.remove(x) removes the first occurrence of x
  • list.count(x) counts the number of x
  • list.pop(i) removes and returns item at position i

Queue and Stack

queue = []
queue.append(item)  # Add to end
queue.pop(0)        # Remove and return first

stack = []
stack.append(item)  # Add to end
stack.pop()         # Remove and return last

Sets

s = set()
s.add(item)
s.remove(item)
if item in s: ...

Substrings

substring = s[start:end:step]

Optional args:

  • start: Starting index (inclusive). Defaults to 0.
  • end: Stopping index (exclusive). Defaults to the end.
  • step: Defaults to 1.

s[::-1] reverses a string.

String Misc

All string functions return values, no in-place modifications.

  • s.strip() removes any leading and trailing whitespaces (also lstrip() and rstrip())
  • ''.join(sorted(s)) sorts the characters in a string
  • s.zfill(n) adds 0 to the beginning until the string is n char long.
  • s.isdigit() returns True if all chars in the string are digits
  • s.isalpha() returns True if all chars in the string are in the alphabet
  • s.startswith(value) returns True if the string starts with value (can be a tuple for multiple checks)
  • s.upper() / s.lower() for case conversion
  • s.replace(old, new, count) returns string with the first count occurences of old replaced by new
  • list(s) converts a string into a list of chars
  • s.split(separator, maxsplit) splits a string (separator defaults to any whitespace, optionally stop splitting after maxsplit splits)
  • s.rsplit() splits from the right

Class

class ClassName:
    """Class description"""

    def __init__(self, arg1, arg2=None):
        """
        Initializes an object

        Args:
            [...]
        """
        self.arg1 = arg1
        self.arg2 = arg2

    def __str__(self):
        return (f"{self.arg1=}, {self.arg2=}")

    def function_a(self, new_arg2):
        self.new_arg2 = new_arg2

obj1 = ClassName("asdf")
print(obj1)

Tests

import pytest

def test_simple():
    assert function_a() == "Hello"

@pytest.mark.parametrize("input, expected", [
    (input1, "Hello"), (input2, "Hi")
])
def test_parameter(input, expected):
    assert function_b(input) == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment