Hi,
Yes it will work.
I think the simplest way if you want to accumulate the gradients associated with a given set of digits:
for digit in selected_digits:
    output[digit].backward(retrain_variables=True)