I occasionally write Python scripts, but I always forget those very basic syntax. So I’m writing this cheat sheet in Python 3.

Iteration

Dictionary iteration for keys:

for key in d:
>>> for key in {1:2, 2:4}:
...   print(key)
...
1
2

Dictionary iteration for values:

for v in d.values():
>>> for v in {1:2, 2:4}.values():
...   print(v)
...
2
4

Dictionary iteration for items (key, value):

for key, value in d.items():
>>> for k, v in {1:2, 2:4}.items():
...   print(k, v)
...
1 2
2 4

Insertion

Append an element into list:

list.append(e)
>>> l = [1, 2]
>>> l.append(3)
>>> l
[1, 2, 3]

Add an element into set:

s.add(e)
>>> s = {1, 2}
>>> s.add(3)
>>> s
{1, 2, 3}

If Statement

Ternary operator:

TrueExpression if Condition else FalseExpression
>>> l = []
>>> 'not empty' if l else 'empty'
'empty'