[Fixed]-Is it more efficient to use function args after branching (Python)?

1👍

From a performance perspective, it makes no difference whether you create data above the if or in the if. Python will only hit the line once and the dict will only be created once. But you should move it above the if for design reasons.

First, don’t repeat yourself – if you can reasonably implement a bit of code in one place, don’t sprinkle it around your code. Suppose you decide a defaultdict is better later, you only have to change it in one place.

Second, placement implies intent. If you put it above your if you’ve made a statement that you plan to use that data structure everywhere. In your current code, readers will ask the same question you do… why wasn’t that above the if? Its kinda trivial but the reading of the code shouldn’t raise more questions.

Leave a comment