Python Cheat Sheet
A dense, scannable reference for syntax you look up again and again — data types, strings, lists, dicts, comprehensions, and common patterns.
Data Types
The built-in types you will use constantly.
basic types
Python
x = 42 # int
x = 3.14 # float
x = "hello" # str
x = True # bool
x = [1, 2, 3] # list
x = (1, 2, 3) # tuple
x = {"a": 1} # dict
x = {1, 2, 3} # set
x = None # NoneType
type(42) # <class 'int'>
type(3.14) # <class 'float'>
type("hi") # <class 'str'>
type([1, 2]) # <class 'list'>
type((1, 2)) # <class 'tuple'>
type({"a": 1}) # <class 'dict'>
type({1, 2}) # <class 'set'>
type(None) # <class 'NoneType'>String Methods
Strings are immutable — every method returns a new string.
string methods
Python
s = " Hello, World "
s.upper() # " HELLO, WORLD "
s.lower() # " hello, world "
s.strip() # "Hello, World"
s.split(",") # [' Hello', ' World ']
"-".join(["a", "b", "c"]) # "a-b-c"
s.replace("Hello", "Hi") # " Hi, World "
s.strip().startswith("Hello") # True
s.strip().endswith("World") # True
name = "Ada"
age = 36
f"{name} is {age} years old" # "Ada is 36 years old"
f"{age * 2}" # "72"
text = "Python"
text[0] # 'P'
text[-1] # 'n'
text[0:3] # 'Pyt'
text[::-1] # 'nohtyP' (reversed)List Methods
Lists are mutable, ordered, and allow duplicates.
list methods
Python
nums = [3, 1, 2] nums.append(4) # [3, 1, 2, 4] nums.extend([5, 6]) # [3, 1, 2, 4, 5, 6] nums.insert(0, 99) # [99, 3, 1, 2, 4, 5, 6] nums.remove(99) # removes first matching value -> [3, 1, 2, 4, 5, 6] nums.pop() # removes & returns last item -> 6 nums.pop(0) # removes & returns item at index -> 3 nums.sort() # sorts in place sorted(nums) # returns a new sorted list, original untouched nums.reverse() # reverses in place nums = [10, 20, 30, 40, 50] nums[1:3] # [20, 30] nums[:2] # [10, 20] nums[2:] # [30, 40, 50] nums[::2] # [10, 30, 50] len(nums) # 5
Dict Methods
Dicts map keys to values and preserve insertion order.
dict methods
Python
d = {"a": 1, "b": 2}
d.get("a") # 1
d.get("z") # None
d.get("z", 0) # 0 (default if key missing)
list(d.keys()) # ['a', 'b']
list(d.values()) # [1, 2]
list(d.items()) # [('a', 1), ('b', 2)]
d.update({"c": 3}) # {'a': 1, 'b': 2, 'c': 3}
d.pop("a") # removes & returns 1 -> {'b': 2, 'c': 3}
d.setdefault("z", 100) # sets 'z' to 100 if not present, returns value
"b" in d # True — membership checks keysComprehensions
Compact syntax for building lists, dicts, sets, and generators.
comprehensions
Python
# list comprehension
squares = [n ** 2 for n in range(10)]
# with a filter
evens = [n for n in range(20) if n % 2 == 0]
# dict comprehension
lengths = {word: len(word) for word in ["a", "bb", "ccc"]}
# set comprehension
unique_lengths = {len(word) for word in ["a", "bb", "ccc", "dd"]}
# generator comprehension (lazy, memory-efficient)
gen = (n ** 2 for n in range(1000000))
next(gen) # 0
# nested comprehension — flatten a matrix
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [n for row in matrix for n in row] # [1, 2, 3, 4, 5, 6]Common Patterns
Idioms that show up in almost every real Python program.
common patterns
Python
# unpacking / swap
a, b = 1, 2
a, b = b, a
# enumerate — index + value
for i, value in enumerate(["x", "y", "z"]):
print(i, value)
# zip — pair up iterables
names = ["Ada", "Grace"]
ages = [36, 85]
for name, age in zip(names, ages):
print(name, age)
# *args and **kwargs
def f(*args, **kwargs):
print(args) # tuple of positional args
print(kwargs) # dict of keyword args
f(1, 2, x=3, y=4)
# ternary expression
status = "adult" if age >= 18 else "minor"
# reading a file safely
with open("data.txt") as f:
contents = f.read()
# file is automatically closed, even if an exception occurs
# try / except / finally
try:
value = int("not a number")
except ValueError:
value = 0
finally:
print("done")
# walrus operator — assign inside an expression
data = [1, 2, 3, 4, 5]
if (n := len(data)) > 3:
print(f"list has {n} items")