Understanding BMLoops: Does every loop enclose a face?
I believe the problem was that I was adding geometry while I was running the function and it right away included the additional loops that were being created in the background.