Refactor to make code more Pythonic