Python Cheatsheet
This cheatsheet focuses on quick reminders of Python-specific syntax and concepts for experienced developers.
List/Sequences & Dictionaries(Hashmaps)β
Sequence Types (List, Tuple, Range)β
Mapping Typesβ
-
- Scroll down the docs for quick shorthand, e.g.
in
,not in
as well as everything that exists on the Dict class def.
- Scroll down the docs for quick shorthand, e.g.
-
Newer versions of python preserve/have insert order, which means you can do things like: pop, reverse, etc.
Creating Dictionariesβ
Dictionaries can be created by several means:
- Use a comma-separated list of key: value pairs within braces:
{'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}
- Use a dict comprehension:
{}, {x: x ** 2 for x in range(10)}
- Use the type constructor:
dict(), dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200)
Moreβ
Remember to refer to Built in Types. It's an excellent reference. For literally most everything you might do: strings, bytes, Sets, Unions, Generics, etc.
π§ Commonly Forgotten Language Basicsβ
-
List Comprehension:
squares = [x*x for x in range(10) if x % 2 == 0]
-
Lambda Functions:
add = lambda x, y: x + y
-
Ternary Operator:
result = "yes" if x > 0 else "no"
-
Unpacking:
a, b, *rest = [1, 2, 3, 4, 5] # rest = [3, 4, 5]
π Loops & Iteratorsβ
Enumerate:
in
is the only keyword for looping- Use range to do a trad loop:
for loopVar; condtion; inc/dec
for i in range(start, stop, step):
Type | for x in ... yields | Notes |
---|---|---|
list | elements | for x in [1, 2] β x = 1 , then x = 2 |
tuple | elements | for x in (1, 2) β x = 1 , then x = 2 |
set | elements | Order is not guaranteed |
str | characters | for c in "abc" β c = "a" , etc. |
dict | keys | for k in {"a": 1} β k = "a" |
dict.items() | (key, value) tuples | for k, v in dict.items() β both key and value |
enumerate() | (index, value) tuples | Use with sequences: for i, x in enumerate(arr) |
zip() | tuples from multiple iterables | for a, b in zip(list1, list2) β parallel unpacking |
custom iterable | whatever its __iter__() yields | You control whatβs yielded |
Zip:
for name, score in zip(names, scores):
print(name, score)
Some Handy Built in Functions
Any / All:
any([False, True]) # True
all([True, True]) # True
Full list of Built in Functions
Error Handling / Safetyβ
-
with
Statement (Context Manager):with open('file.txt') as f:
data = f.read() -
Try/Except/Else/Finally:
try:
...
except ValueError:
...
else:
...
finally:
... -
Finally will always* run, even if the except block is hit.
- Unless
os.exit()
,kill -9
, power loss, etc.
- Unless
Intellisenseβ
-
Type/Function Annotations (IntelliSense):
def greet(name: str) -> str:
return f"Hello {name}" -
Docstring for IntelliSense:
def foo(x: int) -> int:
"""Doubles the input value."""
return x * 2
π Reflection & Metaβ
-
Type Checking:
isinstance(x, int)
-
Dynamic Attributes:
hasattr(obj, 'attr')
getattr(obj, 'attr', default)
setattr(obj, 'attr', value) -
Introspection:
dir(obj)
type(obj)
vars(obj)
π§± No Block Scopeβ
- Variables inside
if
,for
, etc. leak into the outer scope.
π§΅ Syntactic Sugarβ
-
f-Strings:
name = "Alice"
print(f"Hello, {name}") -
Walrus Operator (3.8+):
if (n := len(my_list)) > 10:
print(f"List too long ({n} items)") -
Underscore Usage:
_, val = (1, 2) # Discard value
π§ͺ Comprehensionsβ
- Set and Dict Comprehensions:
squares = {x*x for x in range(5)}
squared_map = {x: x*x for x in range(5)}
𧬠Special Methods (Dunder)β
__init__
,__str__
,__repr__
,__eq__
,__len__
, etc.class Thing:
def __init__(self, name): self.name = name
def __repr__(self): return f"Thing({self.name})"
β οΈ Common Gotchasβ
-
Default args are evaluated once:
def bad(x=[]): ...
-
Strings are immutable; lists are not.
-
No block scope (again, for emphasis).
-
None
,0
,""
,[]
,{}
all evaluate as False.