RuntimeError: stack expects each tensor to be equal size,

How to solve this error? Can someone specifically give me a good example of why this error would happen and how to fix it?
Here is the Error: RuntimeError: stack expects each tensor to be equal size,

The error is raised if the shape of all samples creating the batch differs.
Here is a small example:

class MyDataset(Dataset):
    def __init__(self, transform=None):
        self.data = [torch.randn(3, 224, 224), torch.randn(3, 250, 250)]
        self.transform = transform
        
    def __len__(self):
        return len(self.data)
    
    def __getitem__(self, index):
        x = self.data[index]
        if self.transform:
            x = self.transform(x)
        return x

dataset = MyDataset()

# works
loader = DataLoader(dataset, batch_size=1)
for img in loader:
    print(img.shape)
# torch.Size([1, 3, 224, 224])
# torch.Size([1, 3, 250, 250])

# fails
loader = DataLoader(dataset, batch_size=2)
for img in loader:
    print(img.shape)
# RuntimeError: stack expects each tensor to be equal size, but got [3, 224, 224] at entry 0 and [3, 250, 250] at entry 1

# works again
dataset = MyDataset(transform=transforms.Resize((224, 224)))
loader = DataLoader(dataset, batch_size=2)
for img in loader:
    print(img.shape)
# torch.Size([2, 3, 224, 224])

You could resize or pad the samples to create tensors in the same shape.