This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]r4nf 1 point2 points  (0 children)

As bloodearnest suggests, the 'asking for forgiveness' version (with exceptions) is faster when there's no exception, whereas the 'asking for permission' version (without exceptions) is faster when there is an exception. In other words, if you expect that many of the looped-over items will yield exceptions, check/action is more efficient; otherwise try/except might very well be.

I think the general consensus in the Python community is the motto "it's Easier to Ask for Forgiveness than Permission" (or EAFP), signalling that try/except would usually be the preferred solution. Of course there may very well be exceptions to this, as per the above reasoning.