Let's say that I have an array M and I want to get rid of some blocks of rows. Indeed, I want to do something similar to what the following code implements (where bot_indices, top_indices and M are well defined somewhere else in the code):
for i_bot, i_top in zip(bot_indices, top_indices):
M_new = np.vstack((M_new, M[i_bot:i_top]))
The problem is that, in the first iteration of the for statement, M_new is not defined, so I will get a NameError. To overcome this problem, I've thought to add a try/except statement:
for i_bot, i_top in zip(bot_indices, top_indices):
try:
M_new = np.vstack((M_new, M[i_bot:i_top]))
except NameError:
M_new = M[i_bot:i_top]
Now, the problem is that, if this block of code is embedded within a for or while statement, as M_new already exists the second time that the block shown is accessed, it will end up containing a concatenation of all arrays generated everytime block is accessed. In other words, I would need to "initialize" M_new at the end of the block shown (maybe with a del(M_new)?).
Which is the optimal (in terms of readability, run-time and length of code) way of tackling this problem?