I add a lot of elements to a list of lists. If the list of lists my element should be saved to, does not exist yet, I handle this by catching an exception and adding a new list to my list of lists.
The reason I do this instead of checking every time, if the specified list already exists, is, that I add thousands of elements, to just a few lists. So the case, that the list was not created yet, occurs only a few times. Thus I think it is faster to just raise an exception and handle it, instead of checking list lengths thousands of times.
Here is an example of what I mean:
try:
self.layers[pos].extend(node)
except IndexError:
self.layers.append([])
self.layers[pos].extend(nodes)
(I know the index pos
can not be higher than the length of layers. Thus appending one if an error occurs is always enough)
So back to my question, is that bad coding practice, or is it okay to do it like this for the sake of performance?
I found this discussion about it, but performance was not a topic there.
if
/else
statement as opposed to atry
/catch
. Since testing performed by the OP himself said there is no measurable difference, the right thing to do is to use follow the idiomatic approach for that language. In the case of Python, that would be the code as expressed in the question. Using anif
/else
statement to ask for permission is anti-pythonic.