Essential Python reference covering data types, string methods, list comprehensions, dictionary operations, file I/O, and common built-in functions. A quick lookup for everyday Python programming.
| Code / Syntax | Description |
|---|---|
x = 10 | Integer |
pi = 3.14 | Float |
s = 'hello' | String |
lst = [1, 2, 3] | List (mutable, ordered) |
tup = (1, 2, 3) | Tuple (immutable, ordered) |
d = {'a': 1, 'b': 2} | Dictionary (key-value pairs) |
st = {1, 2, 3} | Set (unique, unordered) |
b = True | Boolean |
n = None | None type (null equivalent) |
by = b'bytes' | Bytes literal |
type(x) | Check the type of a variable |
| Code / Syntax | Description |
|---|---|
s.upper() | Convert to uppercase |
s.lower() | Convert to lowercase |
s.strip() | Remove leading/trailing whitespace |
s.split(',') | Split string into list by delimiter |
','.join(lst) | Join list into string with delimiter |
s.replace('old', 'new') | Replace substring |
s.startswith('he') | Check prefix |
s.endswith('.py') | Check suffix |
f'Hello {name}' | F-string interpolation |
s.find('sub') | Find index of substring (-1 if not found) |
s.zfill(5) | Pad with zeros to specified width |
| Code / Syntax | Description |
|---|---|
[x**2 for x in range(10)] | Basic list comprehension |
[x for x in lst if x > 0] | With condition filter |
[f(x) for x in lst] | Apply function to each element |
[(x, y) for x in a for y in b] | Nested (Cartesian product) |
{x: x**2 for x in range(5)} | Dictionary comprehension |
{x for x in lst if x > 0} | Set comprehension |
(x**2 for x in range(10)) | Generator expression (lazy) |
[row[i] for row in matrix] | Extract column from 2D list |
[x if x > 0 else 0 for x in lst] | Ternary inside comprehension |
[word.lower() for word in sentence.split()] | Transform words in a sentence |
| Code / Syntax | Description |
|---|---|
d['key'] | Access value (raises KeyError if missing) |
d.get('key', default) | Access value with default fallback |
d.keys() | Get all keys as a view |
d.values() | Get all values as a view |
d.items() | Get all (key, value) pairs |
d.update({'c': 3}) | Merge another dict into d |
d | other | Merge dicts (Python 3.9+, returns new dict) |
d.pop('key') | Remove key and return its value |
d.setdefault('key', []) | Get or set default value |
'key' in d | Check if key exists |
del d['key'] | Delete a key-value pair |
| Code / Syntax | Description |
|---|---|
open('file.txt', 'r') | Open file for reading |
open('file.txt', 'w') | Open file for writing (truncates) |
open('file.txt', 'a') | Open file for appending |
with open('f.txt') as f: data = f.read() | Read entire file (context manager) |
f.readlines() | Read all lines into a list |
for line in f: | Iterate over lines (memory efficient) |
f.write('text') | Write string to file |
json.dump(obj, f) | Write JSON to file |
json.load(f) | Read JSON from file |
Path('dir').mkdir(parents=True, exist_ok=True) | Create directory with pathlib |
| Code / Syntax | Description |
|---|---|
len(x) | Length of sequence |
range(start, stop, step) | Generate integer sequence |
enumerate(lst) | Iterate with index and value |
zip(a, b) | Iterate over multiple lists in parallel |
map(fn, lst) | Apply function to each element |
filter(fn, lst) | Filter elements by predicate |
sorted(lst, key=fn, reverse=True) | Return new sorted list |
any(lst) / all(lst) | Check if any/all elements are truthy |
isinstance(x, int) | Check type of object |
min(lst) / max(lst) | Minimum / maximum value |
sum(lst) | Sum of all elements |
Found this cheat sheet useful? Check out our other references and tools.