I think your problems is in order of operations. First you trying to check if i-th instance is valid, and only after it you trying to check if i is not null. Expressions are evaluated from left to right and you should simply first check if i is null and only then attempt to check if i-th instance is valid. I.e. change your if from this:
if is_instance_valid(i) and not(i is null):
to
if not(i is null) and is_instance_valid(i):
also you can probably replace not(i is null)
with i != null