Python Programming Cheat Sheet
Syntax, Built-ins, Tricks & Best Practices
Core Data Types
Type Example Mutable? Notes
int x = 42 No Arbitrary precision
float x = 3.14 No IEEE 754 double
str x = "hello" No Unicode by default
bool x = True No Subclass of int
list x = [1,2,3] Yes Dynamic array
tuple x = (1,2,3) No Immutable list
dict x = {"a":1} Yes Key-value, ordered
(3.7+)
set x = {1,2,3} Yes Unique elements
List Comprehensions
One of Python's most powerful features. Concise and often faster than loops.
# Basic: [expression for item in iterable]
squares = [x**2 for x in range(10)]
# With filter: [expr for item in iterable if condition]
evens = [x for x in range(20) if x % 2 == 0]
# Nested: flatten a 2D list
flat = [x for row in matrix for x in row]
# Dict comprehension
word_len = {w: len(w) for w in ["apple","fig","mango"]}
String Methods
Method Description Example
.split(sep) Split string into list "a,b,c".split(",") → ["a","b","c"]
.join(lst) Join list into string ",".join(["a","b"]) → "a,b"
.strip() Remove whitespace " hi ".strip() → "hi"
.replace(a,b) Replace occurrences "hello".replace("l","r") →
"herro"
.upper()/.lower() Change case "Hi".lower() → "hi"
.startswith(s) Check prefix "hello".startswith("he") →
True
f-strings Format strings f"Value: {x:.2f}"
Useful Built-in Functions
Function Use
enumerate(lst) Loop with index: for i, v in enumerate(lst)
zip(a, b) Pair two iterables: for x, y in zip(a, b)
sorted(lst, key=fn) Return sorted copy without mutating
map(fn, lst) Apply fn to every element
filter(fn, lst) Keep elements where fn returns True
any(iterable) True if any element is truthy
all(iterable) True if all elements are truthy
isinstance(obj, type) Type checking
Pythonic Tricks
Swap variables without temp
a, b = b, a
Unpack iterables
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
Ternary expression
label = "even" if n % 2 == 0 else "odd"
Get dict value with default
count = [Link]("key", 0)
Counter for frequency
from collections import Counter
freq = Counter("banana") # {"a":3,"n":2,"b":1}
defaultdict avoids KeyError
from collections import defaultdict
d = defaultdict(list)
d["key"].append(1) # no KeyError
Error Handling
try:
result = 10 / x
except ZeroDivisionError as e:
print(f'Error: {e}')
except (TypeError, ValueError):
print('Bad input')
finally:
print('Always runs')
Best Practice
Be specific with exceptions. Avoid bare 'except:' — it catches SystemExit and
KeyboardInterrupt too, masking real problems.