Skip to main content
← 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 integer
pi = 3.14Assign a float
name = 'Ada'Assign a string
ok = TrueAssign a boolean
nothing = NoneThe null/absent value
type(x)Get the type of a value
a, b = 1, 2Tuple unpacking into two names
isinstance(x, int)Check if x is an int

Strings & f-strings

f'Hi {name}, you are {age}'Interpolate values into a string
f'{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 membership
text.replace('a', 'b')Replace all occurrences

Numbers & Math

7 // 2Integer (floor) division -> 3
7 % 2Modulo (remainder) -> 1
2 ** 10Exponentiation -> 1024
abs(-5)Absolute value
round(3.567, 1)Round to 1 decimal place
min(3, 9, 1)Smallest of the arguments
sum([1, 2, 3])Sum of an iterable
int('42')Parse a string to an int

Lists

nums = [1, 2, 3]Create a list
nums[0]First element (zero-indexed)
nums[-1]Last element
nums[1:3]Slice items at index 1 and 2
nums[::-1]Reversed copy via slicing
len(nums)Number of items
3 in numsMembership test
list(range(5))Build [0, 1, 2, 3, 4]

List Methods

nums.append(4)Add an item to the end
nums.extend([5, 6])Append all items from an iterable
nums.insert(0, 9)Insert at a given index
nums.pop()Remove and return the last item
nums.remove(2)Remove first matching value
nums.sort()Sort in place ascending
sorted(nums, reverse=True)Return a new descending list
nums.index(3)Find index of first match

Dictionaries

user = {'name': 'Ada', 'age': 36}Create a dict
user['name']Access a value by key
user.get('email', 'n/a')Safe lookup with a default
user['email'] = 'a@b.com'Add or update a key
del user['age']Delete a key
user.keys()View of all keys
user.items()View of (key, value) pairs
{**a, **b}Merge two dicts into a new one

Comprehensions

[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 list

Functions & Default Args

def add(a, b): return a + bDefine a function
def greet(name='world'):Parameter with a default value
add(b=2, a=1)Call using keyword arguments
def total(*args):Accept any number of positional args
def cfg(**kwargs):Accept arbitrary keyword args
square = lambda x: x * xAnonymous (lambda) function
def area(w: int) -> int:Add type hints to a function
return a, bReturn multiple values as a tuple

Conditionals & Loops

if x > 0: ... elif x == 0: ... else: ...Branching with elif/else
label = 'pos' if x > 0 else 'neg'Ternary (conditional) expression
for item in nums:Iterate over a sequence
for i, v in enumerate(nums):Loop with index and value
for k, v in user.items():Loop over dict key/value pairs
for a, b in zip(xs, ys):Iterate two sequences in parallel
for i in range(0, 10, 2):Range with start, stop, step
while n > 0: n -= 1Loop while a condition holds

Classes

class Dog:Define a class
def __init__(self, name): self.name = nameConstructor sets instance state
def bark(self): return f'{self.name}!'Define an instance method
d = Dog('Rex')Create an instance
d.nameAccess an attribute
class Pup(Dog):Inherit from a base class
super().__init__(name)Call the parent constructor
def __repr__(self):Customize the debug string

Reading is good β€” doing is better. Practice Python with interactive, auto-graded lessons.

Start learning Python