Replace loop with list comprehension, try-except block with a safe function, add doc string