Simple tying example for addition function
def add(a: int, b: int) -> int: return a+b
Iterate through list with indices
for i, x in enumerate(list_ab):
Iterate through multiple iterables in parallel
a = [1, 2, 3]
b = [10, 20, 30]
for x, y in zip(a, b):
print(x + y) Dictionary that adds keys if they are not included
```
from collections import defaultdict
counts = defaultdict(int)
for ch in “banana”:
counts[ch] += 1
~~~
What should you be careful about when iterating over a list?
Changing the list while iterating it will also change the iteration, instead iterate over a copy
Create a defaultdict with values
from collections import defaultdict
d = {"a": [1, 2], "b": [9]}
groups = defaultdict(list, d)How to get more info on a function?
help(torch.where) #python torch.where? #Jupyter
How to give a selection of arguments?
``` from typing import Literal
Reduction = Literal[“none”, “mean”, “sum”]
def my_loss(x, reduction: Reduction = “mean”):
…
~~~
How to type optional arguments?
```
Optional[torch.Tensor]
x: torch.Tensor | None = None
~~~
What are common types in PyTorch?
def forward_pass(model: nn.Module, x: torch.Tensor) -> torch.Tensor:
return model(x)How to get infinity and -infinity?
neg_inf = float("-inf")