β All cheat sheets
π
Python Cheat Sheet
A quick-reference Python cheat sheet covering variables, strings, lists, dicts, comprehensions, functions, and more.
Variables & Types
x = 42Assign an integerpi = 3.14Assign a floatname = 'Ada'Assign a stringok = TrueAssign a booleannothing = NoneThe null/absent valuetype(x)Get the type of a valuea, b = 1, 2Tuple unpacking into two namesisinstance(x, int)Check if x is an intStrings & f-strings
f'Hi {name}, you are {age}'Interpolate values into a stringf'{price:.2f}'Format a number to 2 decimals'abc'.upper()Uppercase a string' hi '.strip()Trim surrounding whitespace'a,b,c'.split(',')Split into a list on a delimiter'-'.join(['a', 'b'])Join a list into one string'cat' in textCheck substring membershiptext.replace('a', 'b')Replace all occurrencesNumbers & Math
7 // 2Integer (floor) division -> 37 % 2Modulo (remainder) -> 12 ** 10Exponentiation -> 1024abs(-5)Absolute valueround(3.567, 1)Round to 1 decimal placemin(3, 9, 1)Smallest of the argumentssum([1, 2, 3])Sum of an iterableint('42')Parse a string to an intLists
nums = [1, 2, 3]Create a listnums[0]First element (zero-indexed)nums[-1]Last elementnums[1:3]Slice items at index 1 and 2nums[::-1]Reversed copy via slicinglen(nums)Number of items3 in numsMembership testlist(range(5))Build [0, 1, 2, 3, 4]List Methods
nums.append(4)Add an item to the endnums.extend([5, 6])Append all items from an iterablenums.insert(0, 9)Insert at a given indexnums.pop()Remove and return the last itemnums.remove(2)Remove first matching valuenums.sort()Sort in place ascendingsorted(nums, reverse=True)Return a new descending listnums.index(3)Find index of first matchDictionaries
user = {'name': 'Ada', 'age': 36}Create a dictuser['name']Access a value by keyuser.get('email', 'n/a')Safe lookup with a defaultuser['email'] = 'a@b.com'Add or update a keydel user['age']Delete a keyuser.keys()View of all keysuser.items()View of (key, value) pairs{**a, **b}Merge two dicts into a new oneComprehensions
[x * 2 for x in nums]Map each item to a new list[x for x in nums if x > 0]Filter items with a condition[x * y for x in a for y in b]Nested loops in one list{x for x in nums}Set comprehension (unique values){k: v for k, v in pairs}Build a dict from pairs{w: len(w) for w in words}Map words to their length(x * x for x in nums)Lazy generator expression[y for row in grid for y in row]Flatten a 2D listFunctions & Default Args
def add(a, b):
return a + bDefine a functiondef greet(name='world'):Parameter with a default valueadd(b=2, a=1)Call using keyword argumentsdef total(*args):Accept any number of positional argsdef cfg(**kwargs):Accept arbitrary keyword argssquare = lambda x: x * xAnonymous (lambda) functiondef area(w: int) -> int:Add type hints to a functionreturn a, bReturn multiple values as a tupleConditionals & Loops
if x > 0:
...
elif x == 0:
...
else:
...Branching with elif/elselabel = 'pos' if x > 0 else 'neg'Ternary (conditional) expressionfor item in nums:Iterate over a sequencefor i, v in enumerate(nums):Loop with index and valuefor k, v in user.items():Loop over dict key/value pairsfor a, b in zip(xs, ys):Iterate two sequences in parallelfor i in range(0, 10, 2):Range with start, stop, stepwhile n > 0:
n -= 1Loop while a condition holdsClasses
class Dog:Define a classdef __init__(self, name):
self.name = nameConstructor sets instance statedef bark(self):
return f'{self.name}!'Define an instance methodd = Dog('Rex')Create an instanced.nameAccess an attributeclass Pup(Dog):Inherit from a base classsuper().__init__(name)Call the parent constructordef __repr__(self):Customize the debug stringReading is good β doing is better. Practice Python with interactive, auto-graded lessons.
Start learning Python